c - 使用 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 (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
是有符号或无符号整数类型,则由实现定义。
如果它是无符号的,那么EOF
当255
值char
提升为int
. 并且255 != -1
(-1
是EOF
) 的值。
这就是fgetc
返回 anint
而不是 a的原因char
。所以结果可以直接与int
值相比较EOF
。
似乎在您的系统char
上是无符号的,因此要解决您的问题,请改为定义s
为int
变量:
int s;
推荐阅读
- laravel - Laravel 5.5 类型错误:传递给 Illuminate\Auth\EloquentUserProvider::validateCredentials() 的参数 1 必须是实例
- javascript - 输入类型编号加 10 到值
- php - 使用 mysql_real_escape_string() 代替 IN 运算符中的准备语句
- docker - 在类 io.fabric8.maven.docker.config.ImageConfiguration 中找不到“dockerFileDir”
- c# - WPF 画布在大量 UI 元素上的渲染性能
- javascript - Discord Bot 无法按名称或 ID 找到频道
- spring - 我的 Spring Boot 项目中有一个 CORS 实现我想知道这是正确的方法吗?
- android - 通知不显示 Firebase Android 8
- nginx - 使用 Nginx 提供基于用户代理的聚合物包
- javascript - 如何在 jVectorMap 中以编程方式将区域设置为“悬停”状态?