I am writing a program in C in which I need to create an array of structs, save that array of structs into a file, then open that file, read that file, and copy the contents of that file into an array of structs (this particular struct called "friend" holds three strings). However, if the array holds three friends like this:
John Doe 234-1230 (string, string, string) <br>
Kool Kat 343-3413<br>
Suzie Q 234-1234<br>
I get something like this once I save this array to a file an open it using the open function below:
Joán Doe 234-2132<br>
Kool Kat 343-3413<br>
Suzie Q 234-1234<br>
or
John Doe 234-2132<br>
Kool Kat 343-3413<br>
Suz Q 234-1234<br>
where one string (almost always the first string in the struct) is almost the exact same with one or more random character(s) switched out. Can anyone tell me what is causing this error?
void open(friend* book, int* size){
FILE *pRead;
char address[100];
char answer = 'a';
printf("\nWARNING: Any unsaved data in the current phonebook will be lost!");
printf("\nType the file-name you would like to open(press '1' for the default location):");
scanf("%s", &address);
if(strcmp(address, "1") == 0){
strcpy(address, "default.dat");
}
pRead = fopen(address, "r");
if(pRead == NULL){
printf("\nFile not opened\n");
}else{
int counter = 0;
while(!feof(pRead)){
fscanf(pRead, "%s%s%s", book[counter].pFName, book[counter].pLName, book[counter].pNumber);
counter++;
realloc(book, sizeof(friend) * counter);
}
*size = counter;
fclose(pRead);
printf("\n%s has been loaded into the program!", address);
}
}
Other info: When I keep calling this function on the same file, it will eventually produce the correct strings, which makes me believe my save function is correct. Does this have to do with memory allocation?
Here is my struct code:
typedef struct Contact{ //creates a struct that holds three strings (first name, last name, phone number) (can be referred to as either Contact or friend
char pFName[20]; //first name of friend
char pLName[20]; //last name of contact
char pNumber[12]; //phone number of contact
}friend;