C reading binary files

Possible duplicate:
"while (! feof (file))" is always mistaken

If I write an array to the output file and close the file, then open the file again and read everything until the end of the file is reached, although the file contains only 4 numbers, 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 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; } 
+6
source share
3 answers

feof(fp) becomes false (i.e. a nonzero value) only if you try to read the end of the file. This should explain why the cycle is introduced even more than 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?

+9
source
 while(!feof(f)) { fread(&k,sizeof(int),1,f); printf("a[%d] = %d\n",i,k); /** THIS ASSUMES fread() WAS SUCCESSFUL. **/ i++; } 

Check the end of the file immediately after calling fread() or check the return value of fread() , which returns the number of elements read, which in this case should be 1 . Possible restructuring of the cycle:

 while(1 == fread(&k,sizeof(int),1,f)) { printf("a[%d] = %d\n",i,k); i++; } 

After checking the feof() loop to ensure that the EOF was reached and the loop did not end due to another failure.

+1
source

I have a problem too. Try instead:

 i=0; while(true) { fread(&k,sizeof(int),1,f); if(feof(f)) break; printf("a[%d] = %d\n",i,k); i++; } 

Apparently feof does not return true unless you read the end of the file. What I do when writing arrays in binary files is to write the size first, so I know the exact amount of data that I am going to read when reading.

+1
source

Source: https://habr.com/ru/post/923572/


All Articles