Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C reading binary files [duplicate]

Possible Duplicate:
“while( !feof( file ) )” is always wrong

If I write an array to the output file and I close the file, then open the file again and read everything until end-of-file is reached, although the file contains only 4 number, the program will read and print 5 numbers, why?

Program output:

a[0] = 4
a[1] = 7
a[2] = 12
a[3] = 34
a[4] = 34

save.bin (with a hex editor)

04000000 07000000 0C000000 22000000

#include <stdio.h>
#include <stdlib.h>
#define path "save.bin"

int main(void)
{
  FILE *f=NULL;
  int a[]={4,7,12,34},i,n=4,k;
  f=fopen(path,"wb");
  if(f==NULL)
  {
    perror("Error");
    exit(1);
  }
  for(i=0;i<n;i++)  // or I could use fwrite(a,sizeof(int),n,f);
    fwrite(&a[i],sizeof(int),1,f);
  fclose(f);
  f=fopen(path,"rb");
  if(f==NULL)
  {
    perror("Error");
    exit(1);
  }
  i=0;
  while(!feof(f))
  {
    fread(&k,sizeof(int),1,f);
    printf("a[%d] = %d\n",i,k);
    i++;
  }
  printf("\n");
  fclose(f);
  return 0;
}
like image 681
Cristi Avatar asked Aug 23 '12 15:08

Cristi


1 Answers

feof(fp) becomes false (i.e. non-zero value) only if you tried to read past the end of file. That should explain why the loop is entered one more than what you expect.

From the documentation:

  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 be cleared only by the function clearerr().

Also read the post: Why is “while ( !feof (file) )” always wrong?

like image 144
P.P Avatar answered Sep 24 '22 04:09

P.P