1

In my struct I've got the fields

struct records {
    int link; 
    double gate; 
    char bar; 
};

And in my main()

int main(int argc, char* argv[]){
    struct records rec;

    if(argc<2){//no paramaters
        //return error
    }

    FILE *fp=fopen(argv[1], "rb");

    if(fp==NULL){//no file
         //return error
    }
    while(!feof(fp)){ //fread for each struct field
        fread(&rec.link, sizeof(records.link), 1, fp);
        fread(&rec.gate, sizeof(records.gate), 1, fp);
        fread(&rec.bar, sizeof(records.bar), 1, fp);  
        printf("%d, %f, %c", rec.link, rec.gate, rec.bar);
    } //DONE ON PURPOSE!!! 

    fclose(fp);
    return 0;
}

But this prints out the last record twice. Ive tried variations of while and feof like

while(1){
    if(feof(fp)!=0){
        break;
    fread...
 }

But they all print out the last, and only the last record twice. Every other record is printed out once as intended. Why is this happening and how to I make it work properly?

Alonzo Robbe
  • 465
  • 1
  • 8
  • 23
  • 1
    [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – David Ranieri Aug 13 '17 at 06:36
  • If you read the whole `struct` with a single `fread` you can use its return value to control the loop, for example `while(fread(&rec, sizeof rec, 1, fp) == 1) { . . . };` – Weather Vane Aug 13 '17 at 07:07
  • The man page for `feof` will tell you why it is happening. – Weather Vane Aug 13 '17 at 07:20

0 Answers0