0

I'm trying to replace a data in binary file, but after replacing when I print the data, instead of only 2 data being printed, 3 data is printed where 1 of the data is being repeated

It is like feof() is not working correctly for binary files

#include <stdio.h>

main(void) { 
    FILE* outfile; 

    outfile = fopen("c:\\in.dat","wb"); 

    int data=20;
    int* p =&data; 

    fwrite(p,sizeof(int),1,outfile); 
    data=40; 
    fwrite(&data,sizeof(int),1,outfile);  //this will be replaced by int x 

    int x=100; 
    long int indicate = sizeof(int);
    fseek(outfile,indicate,SEEK_SET); 

    fwrite(&x,sizeof(int),1,outfile); 

    fclose(outfile); 

    FILE* infile;
    infile = fopen("c:\\in.dat","rb"); 

    while(!feof(infile)) {
        fread(&data,sizeof(int),1,infile); 
        printf("%d\n",data); 
    }

    return;             
}
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
  • 1
    You shoudn't use `feof`. Check the return value of `fread` instead. See [this link](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Rishikesh Raje Jan 28 '16 at 08:35
  • Note that you should specify an explicit return type for `main()` — that's [`int`](http://stackoverflow.com/questions/204476/), and you should not have a `return;` in a function returning `int`. You should check that your `fopen()` operations succeed before using the pointer returned. – Jonathan Leffler Jan 28 '16 at 08:37

0 Answers0