简体   繁体   中英

Reading a file with fread, but doesn't work properly

I'm having a problem with the fread() function. I have saved three structures(name,roll no,etc) in a file but when I'm going to read the entire structure, it is only displaying the last one structure that I have saved. Does it have any compatiblity issue or there is a solution for this? The logic to fread it is:

void rfile()
{
  clrscr();
  int n=0;
  FILE *fptr;
  if ((fptr=fopen("test2.rec","rb"))==NULL)
    printf("\nCan't open file test.rec.\n");
  else
  {
    while ( fread(&person[n],sizeof(person[n]),1,fptr)!=1);
    printf("\nAgent #%d.\nName = %s.",n+1,person[n].name);
    printf("\nIdentification no = %d.",person[n].id);
    //printf("\nHeight = %.1f.\n",person[n].height);
    n++;
    fclose(fptr);
    printf("\nFile read,total agents is now %d.\n",n);
  }
}

The problem is while ( fread(&person[n],sizeof(person[n]),1,fptr)!=1); : this will read the file to its end. Hence, the result is that the only person that is placed in your array is the last of the file, and it is placed at n=0 . To correct this, use curly brackets to actually do something in the while loop :

void rfile()
{
    clrscr();
    int n=0;
    FILE *fptr;
    if ((fptr=fopen("test2.rec","rb"))==NULL)
        printf("\nCan't open file test.rec.\n");
    else
    {
        while ( fread(&person[n],sizeof(person[n]),1,fptr)==1){//here !
            printf("\nAgent #%d.\nName = %s.",n+1,person[n].name);
            printf("\nIdentification no = %d.",person[n].id);
            //printf("\nHeight = %.1f.\n",person[n].height);
            n++;
        }//there !
        fclose(fptr);
        printf("\nFile read,total agents is now %d.\n",n);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM