【发布时间】:2021-09-07 16:08:56
【问题描述】:
以下程序编译成功,没有错误,但进入无限循环。
#include <stdio.h>
int main()
{
FILE *ptr;
char s;
ptr = fopen("checkit.txt", "r");
if (ptr == NULL)
perror("Cause of error is: ");
else
{
while (1)
{
s = fgetc(ptr);
if (s == EOF)
break;
printf("%c", s);
}
fclose(ptr);
}
return 0;
}
但编译器显示以下警告。
warning: comparison of constant -1 with expression of type 'char' is always false [-Wtautological-constant-out-of-range-compare]
if (s == EOF)
我在不使用 EOF 的情况下编写了相同的程序,然后它成功编译并运行并打开文件。 以下是没有任何错误或警告的工作程序
#include <stdio.h>
int main()
{
FILE *ptr;
char s;
ptr = fopen("checkit.txt", "r");
if (ptr == NULL)
perror("Cause of error is: ");
else
{
while (1)
{
s = fgetc(ptr);
if (feof(ptr))
break;
printf("%c", s);
}
fclose(ptr);
}
return 0;
}
我无法理解 EOF 不起作用的原因是什么
【问题讨论】:
-
请勿使用
char, unsigned char, signed char声明s。使用int s;。fgetc()通常返回 257 个不同的值。