我编写了以下C代码,将五个名称写入文本文件并在显示器上打印。在从文件中读取数据时,最后一个字符串在屏幕上打印两次。但是为什么......
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1, *fp2, *fp3;
char name[10];
int n,c;
clrscr();
printf("How many names..\n");
scanf("%d", &n);
fp1 = fopen("source.txt", "w");
while( n > 0 )
{
fflush(stdin);
printf("Enter the name\n");
gets(name);
fprintf(fp1,"%s\n", name);
n--;
}
fclose(fp1);
fp1 = fopen("source.txt", "r");
printf(" You entered the following names\n");
while( !feof(fp1) )
{
fscanf(fp1, "%s", name);
printf("%s\t", name);
}
getch();
}
答案 0 :(得分:-1)
因为你没有阅读过手册。
当您处于文件末尾时,C版本feof不会自动返回true。在您尝试阅读某些内容后,它将返回true,以便找不到更多要读取的数据。
其他语言的“feof”可能更容易使用。例如,如果FILEHANDLE上的下一次读取将返回文件末尾,则Perl的eof将返回1 ...