24

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

SamB
  • 9,039
  • 5
  • 49
  • 56
Steffan Harris
  • 9,106
  • 30
  • 75
  • 101

3 Answers3

42

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 5
    I tried this, and it only works if `clear` is called *before* `seekg`. See also here: http://cboard.cprogramming.com/cplusplus-programming/134024-so-how-do-i-get-ifstream-start-top-file-again.html – Frank Jul 09 '12 at 19:23
  • @Frank: Thanks, edited. I suppose you can't operate on a failed stream at all, which makes sense. – Kerrek SB Jul 10 '12 at 07:12
  • For late readers: According to [cpp reference](http://en.cppreference.com/w/cpp/io/basic_istream/seekg), clearing is not necessary any more since C++11... – Aconcagua Jan 17 '18 at 15:24
5

Presumably you mean on an iostream. In this case, the stream's clear() should do the job.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

I agree with the answer above, but ran into this same issue tonight. So I thought I would post some code that's a bit more tutorial and shows the stream position at each step of the process. I probably should have checked here...BEFORE...I spent an hour figuring this out on my own.

ifstream ifs("alpha.dat");       //open a file
if(!ifs) throw runtime_error("unable to open table file");

while(getline(ifs, line)){
         //......///
}

//reset the stream for another pass
int pos = ifs.tellg();
cout<<"pos is: "<<pos<<endl;     //pos is: -1  tellg() failed because the stream failed

ifs.clear();
pos = ifs.tellg();
cout<<"pos is: "<<pos<<endl;      //pos is: 7742'ish (aka the end of the file)

ifs.seekg(0);
pos = ifs.tellg();               
cout<<"pos is: "<<pos<<endl;     //pos is: 0 and ready for action

//stream is ready for another pass
while(getline(ifs, line) { //...// }
user3176017
  • 103
  • 1
  • 10