gpt4 book ai didi

c++ - 到达流的 EOF 时,seekg() 不会设置 eofbit。是设计使然吗?

转载 作者:行者123 更新时间:2023-11-28 02:11:11 25 4
gpt4 key购买 nike

编辑:我原来的测试程序代码中有一个细微的错误:" char=" << aStream.peek()行(可能还有 " input pos=" << aStream.tellg() )修改了流状态标志,因此未报告真实状态。所以那些调用必须从代码中完全删除,否则我们看不到seekg()的真正效果。在州旗上。但是结果仍然相同:eofbit未设置。

原帖:

我尝试检测 std::istream 的 EOF通过调用将输入指针前进 1 步

seekg( 1, std::ios_base::cur )

但是seekg()当它设置 failbit 时,在 EOF 之后移动 1 个位置的流。eofbit永远不会设置。查看此测试程序的输出:

#include <iostream>
#include <sstream>

using namespace std;

void info( int aRelativePos, istream& aStream )
{
cout << "POS=" << aRelativePos <<
" input pos=" << aStream.tellg() <<
" char=" << aStream.peek() <<
"\tGood: " << aStream.good() <<
" Eof: " << aStream.eof() <<
" Bad: " << aStream.bad() <<
" Fail: " << aStream.fail() << "\n";
}

int main()
{
istringstream input ("12");

int i=0;
while ( input.good() )
{
info( i, input );
input.seekg( 1, std::ios_base::cur ); //advance 1 step forward
++i;
}
info ( i, input );

return 0;
}

输出:

POS=0 input pos=0 char=49   Good: 1 Eof: 0 Bad: 0 Fail: 0
POS=1 input pos=1 char=50 Good: 1 Eof: 0 Bad: 0 Fail: 0
POS=2 input pos=-1 char=-1 Good: 1 Eof: 0 Bad: 0 Fail: 0
POS=3 input pos=-1 char=-1 Good: 0 Eof: 0 Bad: 0 Fail: 1

(由 gcc 5.2 使用 -std=c++11 编译。您可以在此处运行此代码:http://coliru.stacked-crooked.com/a/69f4d70e93359423)

此外关于 seekg 的 MS 文档( https://msdn.microsoft.com/en-us/library/y2d6fx99(v=vs.120).aspx ) 表示 C++ 标准不支持文本文件中的相对定位。

但我在标准中找不到这样的信息。可以给我引用吗?

最佳答案

好吧,只要您对标准表示满意,这就是我们从 [istream.unformatted] 获得的行为

basic_istream<charT,traits>& seekg(pos_type pos);

Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that the function first clears eofbit, it does not count the number of characters extracted, and it does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekpos(pos, ios_base::in). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).

所以根据标准,我们将始终清除 eofbit并且在失败时仅设置失败位。试图阅读失败结束是失败的,所以这就是它被设置的原因。刚到达文件末尾并不是失败,因为末尾是一个有效位置。

您可以在这个示例(根据您的代码修改)中看到,一旦我们到达文件末尾,我们仍然很好,然后尝试从那里读取不仅会设置 eofbit还有failbit因为我们在文件末尾并且提取失败

input.seekg(0, std::ios::end);
info (input);
char ch;
input >> ch;
info (input);

输出:

Good: 1 Eof: 0 Bad: 0 Fail: 0
Good: 0 Eof: 1 Bad: 0 Fail: 1

Live Example

关于c++ - 到达流的 EOF 时,seekg() 不会设置 eofbit。是设计使然吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35628288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com