C++ ifstream 的 eof() 是如何工作的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4533063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does ifstream's eof() work?
提问by Chan
#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:
我真的对eof()
功能感到困惑。假设我的 ex.txt 的内容是:
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?
它总是读取一个额外的字符并-1
在使用eof()
. 但是inf >> c
给出了正确的输出是'abc'?谁能帮我解释一下?
回答by Thanatos
-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
)
-1 是get
表示您已到达文件末尾的方式。使用std::char_traits<char>::eof()
(or std::istream::traits_type::eof()
)比较它- 避免 -1,这是一个神奇的数字。(虽然另一个有点冗长 - 你可以随时调用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.
EOF 标志仅在读取尝试越过文件末尾时设置。如果我有一个 3 字节的文件,而我只读取了 3 个字节,则 EOF 是false
,因为我还没有尝试过读取文件的末尾。虽然这对于通常知道其大小的文件来说似乎令人困惑,但直到在某些设备(例如管道和网络套接字)上尝试读取时才会知道 EOF。
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:
第二个示例的工作方式inf >> foo
总是 return inf
,具有尝试读取某些内容并将其存储在foo
. inf
, 在if
or 中while
,将评估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.
}
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.
这就是我们想要的。
回答by Justin Spahr-Summers
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:
EOF 标志仅在读取操作尝试读取文件末尾后才设置。get()
正在返回符号常量traits::eof()
(恰好等于 -1),因为它到达了文件的末尾并且无法读取更多数据,并且只有在那时才会eof()
为真。如果要检查这种情况,可以执行以下操作:
int ch;
while ((ch = inf.get()) != EOF) {
std::cout << static_cast<char>(ch) << "\n";
}
回答by Ken Bloom
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.
iostream 不知道它在文件的末尾,直到它尝试读取文件末尾的第一个字符。
The sample code at cplusplus.comsays to do it like this: (But you shouldn't actually do it this way)
cplusplus.com 上的示例代码说要这样做:(但您实际上不应该这样做)
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 allistream
read operations that return *this
, including the >>
operator)
更好的习惯用法是将读取移动到循环条件中,如下所示:(您可以对所有istream
返回的读取操作执行此操作*this
,包括>>
运算符)
char c;
while(is.get(c))
cout << c;
回答by zeuxcg
eof() checks the eofbit in the stream state.
eof() 检查流状态中的 eofbit。
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.
在每次读取操作中,如果位置在流的末尾并且必须读取更多数据,则 eofbit 设置为 true。因此,在获得 eofbit=1 之前,您将获得一个额外的字符。
The correct way is to check whether the eof was reached (or, whether the read operation succeeded) afterthe 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().
正确的做法是在读操作后检查eof是否到达(或者,读操作是否成功)。这就是您的第二个版本所做的 - 您执行读取操作,然后将结果流对象引用(其中 >> 返回)用作布尔值,从而检查 fail()。