Search code examples
cfilebinaryfwritefread

Reading from a binary file using fread() displays additional characters


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?


Solution

  • 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.