Resetting the End of file state of a ifstream object in C++

Steffan Harris picture Steffan Harris · Oct 7, 2011 · Viewed 24.4k times · Source

I was wondering if there was a way to reset the eof state in C++?

Answer

Kerrek SB picture Kerrek SB · Oct 7, 2011

For a file, you can just seek to any position. For example, to rewind to the beginning:

std::ifstream infile("hello.txt");

while (infile.read(...)) { /*...*/ } // etc etc

infile.clear();                 // clear fail and eof bits
infile.seekg(0, std::ios::beg); // back to the start!

If you already read past the end, you have to reset the error flags with clear() as @Jerry Coffin suggests.