#include <stdio.h>
#pragma pack(push)
#pragma (1)
typedef struct contact {
char firstname [40];
char lastname [40];
char address [100];
char phone[10];
}contact;
#pragma pack(pop)
int main ()
{ FILE *pFile;
contact entry = {"", "", "", ""};
char choice;
pFile = fopen("C:\\contacts.txt", "w+");
if(!pFile){
printf("File could not be open");
return 1;
}
printf("Choose a selection\n\n");
printf("1. Enter First Name\n");
printf("2. Enter Last Name\n");
printf("3. Enter Address\n");
printf("4. Enter Phone Number\n\n");
scanf( "%d", &choice);
switch (choice){
case 1:
printf("First name: \n");
fgets(entry.firstname, sizeof(entry.firstname),pFile);
break;
case 2:
printf("Last name: \n");
fgets(entry.lastname, sizeof(entry.lastname),pFile);
break;
case 3:
printf("Address: \n");
fgets(entry.address, sizeof(entry.address),pFile);
break;
case 4:
printf("Phone Number: \n");
fgets(entry.phone, sizeof(entry.phone),pFile);
break;
default:
printf(" No Choice selected, Ending Address Book Entry system");
break;
}
fwrite(&entry, sizeof(contact), 1, pFile);
printf("Enter a new contact?");
scanf("%s", &choice);
//while(choice != 'n');
fclose(pFile);
getchar();
return 0;
}
This code after I choose an entry and after I put an entry in and press enter it crashes saying Stack around the variable ‘entry’ was corrupted. I’m fairly confident that it is my fwrite function that I’m using. I know the first parameter fwrite looks for is a pointer to an array of elements to be written but I think I’m just confused right now. Any help would be much appreciated.
You should change all your
to
Because you’re reading from the console, not the file.
Also, with
and
you’re trying to read a string and a digit and store it in a
char. They both should beThat said, you should think about rewriting this using
ifstream,cin,getline, andstd::stringto make your life easier if you’re not looking for maximum performance.