Hi,
I have created a program which reads in information from keyboard into a structure and saves the info into a binary file.
I can also get the program to read the information back from the binary file and display it. However, when there is more than 1 records of information in the file, reading it back presents a problem.
I am using the following code to read back from the file:
Code:
fread(&phonebook,sizeof(struct record),1,ptr_myfile);
printf("First Name: %s\n",phonebook.firstname);
printf("Surname: %s\n",phonebook.lastname);
printf("Address: %s\n",phonebook.address);
printf("Phone Number: %s\n",phonebook.phonenumber);
If I double the code to this:
Code:
fread(&phonebook,sizeof(struct record),1,ptr_myfile);
printf("First Name: %s\n",phonebook.firstname);
printf("Surname: %s\n",phonebook.lastname);
printf("Address: %s\n",phonebook.address);
printf("Phone Number: %s\n",phonebook.phonenumber);
fread(&phonebook,sizeof(struct record),1,ptr_myfile);
printf("First Name: %s\n",phonebook.firstname);
printf("Surname: %s\n",phonebook.lastname);
printf("Address: %s\n",phonebook.address);
printf("Phone Number: %s\n",phonebook.phonenumber);
It will read the two records of information in the file. However, that is not practical and I am looking for a way to have it loop until the end of file is reached.
So, after alot of researching online, I used the code:
Code:
while ((ch=getc(ptr_myfile) != EOF))
{
fread(&phonebook,sizeof(struct record),1,ptr_myfile);
printf("First Name: %s\n",phonebook.firstname);
printf("Surname: %s\n",phonebook.lastname);
printf("Address: %s\n",phonebook.address);
printf("Phone Number: %s\n",phonebook.phonenumber);
printf("\n");
}
While this works, the problem is that it strips each field in the first record of the first character, each field in the second record of the first and second characters, and so on. The problem, I believe, being with the 'getc' function.
So Im wondering if there is any other way I can read all records in the binary file until the EOF is reached?
Thanks in advance.
S.