我正在做一个非常简单的家庭作业,需要我输出一个文件的内容,但我在做任何事情之前意外地到达了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");
}发布于 2017-05-22 23:39:29
根据feof()的手册页
函数feof()测试文件结束指示符
for the stream pointed to by stream, _returning nonzero if it is set_.因此,唯一的期望是返回值为0或非零。
因此,值16没有任何问题
以下是代码的建议版本:
、、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.
bighttps://stackoverflow.com/questions/44109894
复制相似问题