0

My question is about this fread() function that seems to be confusing for the time being. I create a binary file and put inside of it the values 1,2 and 3. And then I try to read the file and when I do using fread() it shows it like 1233 not 123.


#include <stdio.h> 
#include <stdlib.h>     
main ()
{
  int x=1,y=2,z=3,i,j;
  FILE *f;
  f=fopen("Werid.bin","wb");
  fwrite(&x,sizeof(int),1,f);
  fwrite(&y,sizeof(int),1,f);
  fwrite(&z,sizeof(int),1,f);
  fclose(f);
  f=fopen("Werid.bin","rb");
  if (!f) perror("X");
  while(!feof(f))
    {
      fread(&j,sizeof(int),1,f);
      printf("%d",j);
    }
  fclose(f);
}

Why?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

2

Change this

while(!feof(f))

to

while(fread(&j,sizeof(int),1,f) == 1)

From linux feof() manual

The function feof() tests the end-of-file indicator for the stream pointed to by stream, returning nonzero if it is set. The end-of-file indicator can only be cleared by the function clearerr().

The feof() will return true after you try to call fread() at the end of file i.e. after you read the last number, you will need to call fread() again to set the end-of-file indicator.

So the loop will be executed one more time after the last read, and since it does not read anything but rather returns an error, it does not change the value of j either, so the previous value 3 is printed again.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • Why did that work? Can you elaborate more? @iharob – user3785612 Jan 16 '15 at 19:49
  • @user3785612: Read the question and answer's of which this question is a duplicate. Basically, you are printing the value before you check whether the last read succeeded, so when it fails, you print the last value a second time, hence the duplicated 3. – Jonathan Leffler Jan 16 '15 at 19:51