首页 > 解决方案 > 使用 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 不起作用的原因是什么

标签: cfileeof

解决方案


如果char是有符号或无符号整数类型,则由实现定义。

如果它是无符号的,那么EOF255char提升为int. 并且255 != -1(-1EOF) 的值。

这就是fgetc返回 anint而不是 a的原因char。所以结果可以直接与int值相比较EOF

似乎在您的系统char上是无符号的,因此要解决您的问题,请改为定义sint变量:

int s;

推荐阅读