2014-11-14 53 views
-3

我遇到fread()函数有问题。 我在文件中保存了三个结构(名称,卷号等),但是当我要读取整个结构时,它只显示我已保存的最后一个结构。它是否有任何兼容性问题或有解决方案?使其变为的逻辑是:用fread读取文件,但无法正常工作

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); 
    } 
} 
+0

此“void rfile()”是在“main()”中调用的函数。 – 2014-11-14 17:46:47

+0

这是严格的CIO,我删除了C++标记。 – Borgleader 2014-11-14 17:46:58

回答

1

问题是while (fread(&person[n],sizeof(person[n]),1,fptr)!=1);:这会将文件读到最后。因此,结果是数组中放置的唯一person是该文件的最后一个,它位于n=0。若要更正此问题,请使用大括号在while循环中实际执行某些操作:

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); 
    } 
} 
+0

你是对的!我错过了这一个!我编辑并更正了它。 – francis 2014-11-14 21:00:55