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

后端 未结 3 1268
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题