Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);

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

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.

This does not work: because if you call:

int count = in.gcount()  // Charecters readed from input.

you will notice that count == 0. Meaning it has not read anything at all.

Hence the question: How can you rewind the file after you get to the end of the file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
652 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

Explanation

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

From the standar specification:

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

And we can read in UnformattedInputFunction:

The following standard library functions are UnformattedInputFunctions:

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

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.

That's why!!

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

My guess

Why seekg does not work when failbit is activated?

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, using seekg is error prone or might shows undefined behaviour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...