在击中文件结尾后回滚ifstream对象 [英] Rewind an ifstream object after hitting the end of file

查看:173
本文介绍了在击中文件结尾后回滚ifstream对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个包含几个字符(可以说10个)的文本文件,您可以尝试从中读取1000个字符。

Having a text file with a few characters (lets say 10), you can try to read 1000 characters from it.

char *buf = new char[1000];
ifstream in("in.txt");
in.read(buf, 1000);

这当然会设置 eofbit 标志(和

This, of course will set the eofbit flag (and the failbit too), however, you will be able to obtain the desired characters.

现在,假设您想要读取所需的字符,您可以使用 =nofollow (从头开始):

Now, suppose you want to read the file again (from the beginning):

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

因此,问题是:如何在文件结束后回滚文件?

Hence the question: How can you rewing the file after hit end of file?

推荐答案

解决方案



使用清除以清除ifstream的状态,然后调用 seekg 请务必先检查,如果您以后不需要了解状态。

Solution

Use clear for cleaning the state of the ifstream before call seekg. Be sure to check first if you don't will need to know the state later.

in.clear();
in.seekg(0);



说明



seekg 设置输入位置,但不会清除状态位 failbit 因此, ifstream 实例认为有错误。

Explanation

seekg sets the input position, but doesn't clear state bit failbit so, the ifstream instance "thinks" there is something wrong yet.

标准规格:


std :: basic_istream :: seekg 的行为与 UnformattedInputFunction ,但gcount()不受影响。

std::basic_istream::seekg behaves as UnformattedInputFunction, except that gcount() is not affected.

我们可以在 UnformattedInputFunction


以下标准库函数为 UnformattedInputFunctions

basic_istream :: seekg ,但它首先清除eofbit ,且不修改gcount

basic_istream::seekg, except that it first clears eofbit and does not modify gcount

在问题示例中,如果打印seekg之前和之后的状态,您将得到:

In the question example if you print the state before and after the seekg you get:

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 doesn请清除 failbit ,并且出于某些实现原因,它不工作

seekg doesn't clear failbit and for some implementation reason, it doesn't works with such bit activated.

为什么 seegk 故障位激活时无效?

它与事实不同,只有当流到达文件的末尾时才被激活。并且可能是在故障位激活后,使用 gseek 是容易出错或可能显示未定义的行为。

It has to do with the fact this bit is not only activated when the stream reach the end of the file. And it might be situations in which after failbit is activated, use gseek is error prone or might shows undefined behaviour.

这篇关于在击中文件结尾后回滚ifstream对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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