2
int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) {
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
    }

    return 0;
}

temp.txt是一个缓慢增加的日志文件,因此该程序可以读取 EOF。在它第一次遇到 EOF 之后,我认为它应该停止获取temp.txt的新添加数据,而它就像tail -f temp.txt并继续打印文件的新行一样。

是的,我知道有一个无限循环。问题是我想,当fgetc第一次遇到 EOF 时,它应该在 struct fp中做一些记录,并且fgetc的下一次调用应该检查这一点并立即返回 EOF。为什么它继续读取磁盘上的数据,它没有到达文件末尾?这是预期的行为吗?

4

5 回答 5

2

快速回答是,没有break退出while循环。

当它读取时EOF,它会循环回来并坚持下去c = fgetc(fp);

如果您需要它在到达 EOF 时停止阅读,您可以添加else

while (1) {
    c = fgetc(fp);
    if (EOF != c) {
        putchar(c);
    } else {
        // reached the EOF
        break;
    }
}
于 2013-07-26T12:59:59.010 回答
1

但是,您并没有告诉它在找到 EOF 时离开 while 循环,您只是说如果您确实找到了 EOF,就不要对它做任何事情。您需要从循环中放置一个条件中断或有一个条件,直到 while 循环将继续。

于 2013-07-26T13:00:22.807 回答
0
int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) {
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
        else
          break; //this will fix your problem of infinite loop even finding EOF
    }

    return 0;
}
于 2013-07-26T13:04:58.080 回答
0

IMO 当你这样做时会更好看

int c = 0;
while ((c = fgetc(fp)) != EOF)
{
    putchar(c);
}
于 2013-07-26T13:05:12.767 回答
0
int main(int argc, char *argv[])
{
    int c = EOF;
    FILE *fp = fopen("./temp.txt", "r");
    assert(fp!=NULL);
    while (1) { // here
        c = fgetc(fp);
        if (EOF != c) {
            putchar(c);
        }
    }

    return 0;
}

这是因为您有一个无法停止的无限循环(某些信号除外)。这个程序将temp.txt永远阅读。

于 2013-07-26T13:00:54.560 回答