ifstream 的 eof() 是如何工作的?

发布于 2024-10-08 21:02:58 字数 613 浏览 3 评论 0原文

#include <iostream>
#include <fstream>

int main() {
    std::fstream inf( "ex.txt", std::ios::in );
    while( !inf.eof() ) {
        std::cout << inf.get() << "\n";
    }
    inf.close();
    inf.clear();
    inf.open( "ex.txt", std::ios::in );
    char c;
    while( inf >> c ) {
        std::cout << c << "\n";
    }
    return 0;
}

我对 eof() 函数真的很困惑。假设我的 ex.txt 的内容是:

abc

使用 eof() 读取时,它总是读取一个额外的字符并显示 -1。但是 inf >> c 给出了正确的输出,即“abc”?谁能帮我解释一下吗?

#include <iostream>
#include <fstream>

int main() {
    std::fstream inf( "ex.txt", std::ios::in );
    while( !inf.eof() ) {
        std::cout << inf.get() << "\n";
    }
    inf.close();
    inf.clear();
    inf.open( "ex.txt", std::ios::in );
    char c;
    while( inf >> c ) {
        std::cout << c << "\n";
    }
    return 0;
}

I'm really confused about eof() function. Suppose that my ex.txt's content was:

abc

It always reads an extra character and shows -1 when reading using eof(). But the inf >> c gave the correct output which was 'abc'? Can anyone help me explain this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灯下孤影 2024-10-15 21:02:58

-1 是 get 表示已到达文件末尾的方式。使用 std::char_traits::eof() (或 std::istream::traits_type::eof())进行比较 - 避免 -1,这是一个神奇的数字。 (尽管另一个有点冗长 - 您始终可以只调用 istream::eof)

仅当读取尝试读取文件末尾之后时才会设置 EOF 标志嗯>。如果我有一个 3 字节的文件,并且我只读取了 3 个字节,则 EOF 为 false,因为我还没有尝试读取超过文件末尾的内容。虽然这对于通常知道其大小的文件来说似乎令人困惑,但直到在某些设备(例如管道和网络套接字)上尝试读取时才知道 EOF。

第二个示例的工作方式为 inf >>> foo 将始终返回 inf,其副作用是尝试读取某些内容并将其存储在 foo 中。 infifwhile 中,如果文件“良好”,则计算结果为 true:没有错误,没有EOF。因此,当读取失败时,inf 的结果为 false,并且循环会正确中止。然而,考虑这个常见的错误:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

然而,这:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

这就是我们想要的。

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

囍笑 2024-10-15 21:02:58

仅当读取操作尝试读取文件末尾之后,才会设置 EOF 标志。 get() 返回符号常量 traits::eof() (恰好等于 -1),因为它到达文件末尾并且无法读取任何内容更多数据,只有此时 eof() 才会为 true。如果您想检查这种情况,可以执行以下操作:

int ch;
while ((ch = inf.get()) != EOF) {
    std::cout << static_cast<char>(ch) << "\n";
}

The EOF flag is only set after a read operation attempts to read past the end of the file. get() is returning the symbolic constant traits::eof() (which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof() be true. If you want to check for this condition, you can do something like the following:

int ch;
while ((ch = inf.get()) != EOF) {
    std::cout << static_cast<char>(ch) << "\n";
}
无所谓啦 2024-10-15 21:02:58

iostream 不知道它位于文件末尾,直到它尝试读取文件末尾后面的第一个字符。

cplusplus.com 上的示例代码说要这样做:(但是你实际上不应该这样做)

  while (is.good())     // loop while extraction from file is possible
  {
    c = is.get();       // get character from file
    if (is.good())
      cout << c;
  }

更好的习惯用法是将读取移动到循环条件中,如下所示:
(您可以使用返回 *this所有 istream 读取操作来执行此操作,包括 >> 运算符)

  char c;
  while(is.get(c))
    cout << c;

iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.

The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)

  while (is.good())     // loop while extraction from file is possible
  {
    c = is.get();       // get character from file
    if (is.good())
      cout << c;
  }

A better idiom is to move the read into the loop condition, like so:
(You can do this with all istream read operations that return *this, including the >> operator)

  char c;
  while(is.get(c))
    cout << c;
月亮坠入山谷 2024-10-15 21:02:58

eof() 检查流状态中的 eofbit。

在每次读取操作中,如果位置位于流末尾并且必须读取更多数据,则 eofbit 设置为 true。因此,在 eofbit=1 之前,您将获得一个额外的字符。

正确的方法是在读操作之后检查是否达到eof(或者读操作是否成功)。这就是您的第二个版本所做的 - 您执行读取操作,然后使用生成的流对象引用(>> 返回)作为布尔值,这将导致检查失败()。

eof() checks the eofbit in the stream state.

On each read operation, if the position is at the end of stream and more data has to be read, eofbit is set to true. Therefore you're going to get an extra character before you get eofbit=1.

The correct way is to check whether the eof was reached (or, whether the read operation succeeded) after the reading operation. This is what your second version does - you do a read operation, and then use the resulting stream object reference (which >> returns) as a boolean value, which results in check for fail().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文