为什么这段代码会读取文件中的最后一次?谁能帮我 ?? feof和循环有什么问题? 为什么总是不正确,我试了太多次?
提前致谢
char n [120];
char p[120];
char e [120];
char g [120];
int no;
FILE *fptr;
fptr=fopen("answer.txt","ra+");
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
printf("%6s %-20s %-15s %-15s %-15s\n","Acct#","Name","Phone","Email","Group" );
printf("------ -------------------- ------------- ------------------- --------------- \n");
currentc=firstc;
while(!feof(fptr))
{
currentc= (struct contact *) malloc(sizeof(struct contact ));
fscanf(fptr,"%d",&no);
currentc->number=no;
printf("%6d: ",currentc->number);
fscanf(fptr,"%s",&n);
strcpy(currentc->name,n);
printf("%-20s ",currentc->name);
fscanf(fptr,"%s",&p);
strcpy(currentc->phone,p);
printf("%-15s ",currentc->phone);
fscanf(fptr,"%s",&e);
strcpy(currentc->email,e);
printf("%-20s ",currentc->email);
fscanf(fptr,"%s",&g);
strcpy(currentc->group,g);
printf("%-15s ",currentc->group);
}
fclose(fptr);
}
答案 0 :(得分:1)
改变你的状态。而不是检查!feof(文件),检查fscanf是否成功(即fscanf()== 1)。 fscanf如果成功则返回1,否则返回0.
调用的最后一个fscanf读取文件的最后一行,然后检查while循环条件!feof(file)。这是真的,因为没有达到文件的结尾。所以循环再次执行。
答案 1 :(得分:0)
原因是你正在读取while块中的多行,但是每多行检查一次feof。问题是最后一个空行,它会尝试读取另一组值。但由于它们是空的,之前的值正在打印。
简单回答是阅读一次并在打印前重新检查:
while(!feof(fptr))
{
fscanf(fptr,"%d", &no);
fscanf(fptr,"%s", &n);
fscanf(fptr,"%s", &p);
fscanf(fptr,"%s",&e);
fscanf(fptr,"%s",&g);
if(!feof(fptr)){
printf("%6d: ", no);
printf("%-20s ", n);
printf("%-15s ", p);
printf("%-20s ", e);
printf("%-15s \n", g);
}
}