[英]Rewind an ifstream object after hitting the end of file
有一个包含几个字符(比如说 10 个)的文本文件,您可以尝试从中读取 1000 个字符。
char *buf = new char[1000];
ifstream in("in.txt");
in.read(buf, 1000);
当然,这将设置eofbit标志(以及故障位),但是,您将能够获得所需的字符。
现在,假设您想再次读取文件(从头开始):
in.seekg(0); // Sets input position indicator.
in.read(buf, 100); // Try to read again.
这不起作用:因为如果你打电话:
int count = in.gcount() // Charecters readed from input.
你会注意到count == 0
。 这意味着它根本没有阅读任何内容。
因此,问题是:到达文件末尾后如何倒带文件?
在调用seekg
之前使用clear 清除ifstream 的状态。 如果您以后不需要知道状态,请务必先检查。
in.clear();
in.seekg(0);
seekg设置光标位置,但不清除状态位failbit因此, ifstream实例“认为”有问题。
从标准规范:
std::basic_istream::seekg 的行为与UnformattedInputFunction 相同,但 gcount() 不受影响。
我们可以在UnformattedInputFunction 中读取:
以下标准库函数是UnformattedInputFunctions :
basic_istream::seekg ,除了它首先清除 eofbit并且不修改 gcount
在问题示例中,如果您在 seekg 之前和之后打印状态,您会得到:
cout << "State before seekg: " << in.rdstate() << endl; // Prints 3 (11 in binary) failbit and eofbit activated.
in.seekg(0);
cout << "State after seekg: " << in.rdstate() << endl; // Prints 2 (10 in binary) just failbit activated.
这就是为什么!!
seekg 不清除failbit并且由于某些实现原因,它不适用于激活的此类位。
激活failbit时为什么seekg
不起作用?
这与这个位不仅在流到达文件末尾时才被激活的事实有关。 并且可能是在激活 failbit 后,使用seekg
容易出错或可能显示未定义行为的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.