当最后一行看完之后叫不的feof()工作? [英] Does feof() work when called after reading in last line?

查看:125
本文介绍了当最后一行看完之后叫不的feof()工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是用下面的语句读取的字符串:

I just read in a string using the following statement:

fgets(string, 100, file);

刚读这个字符串是最后一道防线。如果我称之为的feof()现在将它返回TRUE?它是与调用的feof()就在开始任何行前阅读?

This string that was just read in was the last line. If I call feof() now will it return TRUE? Is it the same as calling feof() right at the start before reading in any lines?

推荐答案

简短的答案是即可。这是为什么:

The short answer is NO. Here is why:

如果与fgets 成功地读取的'\\ n'在该行的末尾,最终OF-在 FILE文件指示标志结构尚未确定。因此,的feof()将返回 0 ,就像它应该在阅读任何东西,甚至在一个空文件之前。

If fgets successfully read the '\n' at the end of the line, the end-of-file indicator in the FILE structure has not been set. Hence feof() will return 0, just like it should before reading anything, even on an empty file.

的feof()只能用于和文件结束-区分后的输入操作失败的读错误条件。同样, FERR()可用于检查读取错误后输入操作失败。

feof() can only be used to distinguish between end-of-file and read-error conditions after an input operation failed. Similarly, ferr() can be used to check for read-error after an input operation failed.

程序员通常忽略文件结束之间的差异,并读取错误。因此,它们只依赖于检查所述输入操作是成功还是失败。因此,他们从来没有使用的feof(),你也应该这样。

Programmers usually ignore the difference between end-of-file and read-error. Hence they only rely on checking if the input operation succeeded or failed. Thus they never use feof(), and so should you.

该行为是作为的有点类似错误号错误号是由一些库函数发生错误时设置或失败。它不是建立在成功重置为 0 。检查错误号后一个函数调用只有在操作失败的和有意义如果错误号是在函数调用前清 0

The behavior is somewhat similar as that of errno: errno is set by some library functions in case of error or failure. It is not reset to 0 upon success. Checking errno after a function call is only meaningful if the operation failed and if errno was cleared to 0 before the function call.

如果您要检查,如果你真的达到文件中,你需要尝试和读取额外投入。例如,您可以使用此功能:

If you want to check if you indeed reached to the of file, you need to try and read extra input. For example you can use this function:

int is_at_end_of_file(FILE *f) {
    int c = getc(file);
    if (c == EOF) {
        return 1;
    } else {
        ungetc(c, file);
        return 0;
    }
}

但是读取额外输入,如果从控制台读取可能不值得:它会需要用户键入额外输入,将保存在输入信息流中。如果从管道或设备读取,副作用可能更成问题。唉,有测试如果文件流与实际的文件关联的可移植的方法。

But reading extra input might not be worthwhile if reading from the console: it will require for the user to type extra input that will be kept in the input stream. If reading from a pipe or a device, the side effect might be even more problematic. Alas, there is no portable way to test if a FILE stream is associated with an actual file.

这篇关于当最后一行看完之后叫不的feof()工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆