我正在做一个非常简单的作业,需要输出文件的内容,但在做任何事情之前我意外地到达了 EOF。 该文件仅包含单词“pig”,并且由于某种原因 EOF 返回 16。我正在使用 Dev-Cpp 并且该程序是用 C 语言编写的。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp=fopen("C:/Users/myusername/Desktop/numeri.txt", "r");
char c;
if (fp!=NULL)
{
printf ("File opened correctly.\n");
c=fgetc(fp);
printf("%d\n", feof(fp)); //FEOF EQUALS 16 FOR SOME REASON
while (feof(fp)==0)
{
putchar(c);
c=fgetc(fp);
}
fclose(fp);
system("PAUSE");
return 0;
}
else
{
printf ("File cannot be opened.\n");
system("PAUSE");
exit(1);
}
system("PAUSE");
}
最佳答案
根据 feof()
的手册页:
函数 feof() 测试文件结束指示器
对于stream指向的流,
如果设置则返回非零。
因此唯一的期望是返回值是 0 或非零。
所以值16
没有任何问题
这是代码的建议版本:
- 编译干净
- 它执行所需的功能
- 它实现了对问题的评论
- 通过单个空行分隔代码块(for、if、else、while、do...while、switch、case、default),可以增强可读性和理解性。
现在是代码
#include <stdio.h> // fopen(), printf(), perror(). fclose(), fgetc()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main( void )
{
FILE *fp = fopen("big.txt", "r");
if (fp!=NULL)
{
printf ("File opened correctly.\n");
int c=fgetc(fp);
while (EOF != c)
{
putchar(c);
c=fgetc(fp);
}
fclose(fp);
return 0;
}
else
{
perror ("File cannot be opened.\n");
exit( EXIT_FAILURE );
}
}
注意:文件:big.txt
仅包含big
这是结果输出:
File opened correctly.
big
关于c - EOF 在...EOF 之前到达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109894/