我遇到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 :(得分: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);
}
}