【问题标题】:Resetting the End of file state of a ifstream object in C++在 C++ 中重置 ifstream 对象的文件结束状态
【发布时间】:2011-12-02 15:38:58
【问题描述】:

我想知道是否有办法在 C++ 中重置 eof 状态?

【问题讨论】:

    标签: c++ file iostream


    【解决方案1】:

    对于文件,您可以搜索到任何位置。例如,要倒回到开头:

    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!
    

    如果您已经阅读到最后,则必须按照@Jerry Coffin 的建议使用clear() 重置错误标志。

    【讨论】:

    • 我试过这个,它只有在clear被调用之前 seekg时才有效。另请参阅:cboard.cprogramming.com/cplusplus-programming/…
    • @Frank:谢谢,已编辑。我想您根本无法对失败的流进行操作,这是有道理的。
    • 对于迟到的读者:根据cpp reference,从 C++11 开始不再需要清除...
    【解决方案2】:

    大概您的意思是在 iostream 上。在这种情况下,流的clear() 应该可以完成这项工作。

    【讨论】:

      【解决方案3】:

      我同意上面的答案,但今晚遇到了同样的问题。所以我想我会发布一些更多教程的代码,并在流程的每个步骤中显示流位置。我可能应该在这里检查一下...之前...我花了一个小时自己解决这个问题。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        相关资源
        最近更新 更多