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

后端 未结 3 1261
耶瑟儿~
耶瑟儿~ 2020-12-18 19:03

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

相关标签:
3条回答
  • 2020-12-18 19:23

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

    0 讨论(0)
  • 2020-12-18 19:36

    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.

    0 讨论(0)
  • 2020-12-18 19:43

    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) { //...// }
    
    0 讨论(0)
提交回复
热议问题