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

30,401

Solution 1

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.

Solution 2

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

Solution 3

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) { //...// }
Share:
30,401

Related videos on Youtube

Steffan Harris
Author by

Steffan Harris

I'm a student programmer.

Updated on March 11, 2020

Comments

  • Steffan Harris
    Steffan Harris about 4 years

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

  • Frank
    Frank almost 12 years
    I tried this, and it only works if clear is called before seekg. See also here: cboard.cprogramming.com/cplusplus-programming/…
  • Kerrek SB
    Kerrek SB almost 12 years
    @Frank: Thanks, edited. I suppose you can't operate on a failed stream at all, which makes sense.
  • Aconcagua
    Aconcagua over 6 years
    For late readers: According to cpp reference, clearing is not necessary any more since C++11...