当我读取文件时,它不包括最后一条记录,所以在这种情况下Bill Biking不显示
以下是hobbies.dat
文件:
Bob Running
Josh Swimming
Bill Biking
这是程序的代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char name[30];
char hobby[30];
char *filename = "hobbies.dat";
fp = fopen(filename, "r");
if (fp == NULL) {
printf("File cannot open");
perror("The following error has occured");
}
else
{
printf("\nName\tHobby\n\n");
fscanf(fp, "%s%s", name, hobby);
while (!feof(fp))
{
printf("%s\t%s\n", name, hobby);
fscanf(fp, "%s%s", name, hobby);
}
}
system("pause");
return 0;
}
答案 0 :(得分:0)
按如下方式更改循环:
...
else
{
printf("\nName\tHobby\n\n");
while (!feof(fp))
{
fscanf(fp, "%s%s", name, hobby);
printf("%s\t%s\n", name, hobby);
}
}
...
我改变了这一点,因为您需要在再次fscanf
之前进行最终打印并达到EOF。