I am reading from a file using Binary File IO function fread When i run the program final entry is printed out twice
FILE *fp;
struct entry temp;
if (fp = fopen("recs.bin","rb"))
{
while (!feof(fp))
{
fread(&temp,sizeof (struct entry),1,fp);
printf("%s %s %s \n", temp.name ,temp.design ,temp.contact);
}
fclose(fp);
else
{
printf("\error opening file\n");
}
When i run the code the output is as following
Pfor.ABC Professor 9867552
Sir Blah lecturar 9237434
Miss etc Asst. Porfessor 03847363
Miss etc Asst. Porfessor 03847363
I always get the last entry twice
I tried by printing beofre reading like below
while (!feof(fp))
{
printf("%s %s %s \n", temp.name ,temp.design ,temp.contact);
fread(&temp,sizeof (struct entry),1,fp);
}
now output is
#gd^&!d $!du(! #$@%@22 //Some garbage values
Pfor.ABC Professor 9867552
Sir Blah lecturar 9237434
Miss etc Asst. Porfessor 03847363
Now the printing twice is solved but a garbage value is being printed
I think its the problem in feof(fp) but cant figure it out
Answer
The double handling of the last entry comes from using feof
, which is usually not a good way to control file Input loops.
Instead, you should check the return value of the reading functions fgetc
, fgets
and, in your case, fread
. fread
returns the number of items, i.e. the number of blocks of size
bytes, read. If that is smaller than the number of items to read, you have an incomplete read. So:
while (fread(&temp, sizeof(struct entry), 1, fp) == 1) {
printf("%s %s %s \n", temp.name, temp.design, temp.contact);
}
As long as you have a complete read, print out the data.
Others have already pointed out that printing the (uninitialised) data before reading it leads to your garbage values. If you must use such a set-up, you should at least place one read before the loop.
No comments:
Post a Comment