I was wondering if there was a way to reset the eof s开发者_如何学Ctate in C++?
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.
Presumably you mean on an iostream. In this case, the stream's clear()
should do the job.
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) { //...// }
精彩评论