Steffan Harris
Steffan Harris

Reputation: 9336

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

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

Upvotes: 24

Views: 38909

Answers (3)

user3176017
user3176017

Reputation: 103

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) { //...// }

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477640

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.

Upvotes: 43

Jerry Coffin
Jerry Coffin

Reputation: 490728

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

Upvotes: 6

Related Questions