zoukankan      html  css  js  c++  java
  • 关于seekg失效的问题

    当file.eof()=1的时候seekg就不好用了,
    当file.eof()=0的时候seekg是好用的。

    也就是说当一个文件读到尾部以后,
    不能再用seekg来移动或者定位了。
    通过建立该文件新的对象能解决这个问题。

    如果只是输出的话可以用streambuf的rdbuf

    #include<fstream>
    #include<iostream>
    #include<string>
    using namespace std;
    
    int main(){
        ofstream ofile("test.txt");
        ofile<<"hello this is testing fstream!";
        ofile<<endl;
        ofile.close();
    
        ifstream ifile("test.txt");
        string line;
        for(int i=0; i<3; i++){
            cout<<"this is "<<i<<" file"<<endl;
            ifile.clear();
            while(getline(ifile,line)){
                cout<<line<<endl;
            }
            cout<<"eof: "<<ifile.eof()<<endl;
            ifile.seekg(0,ios::beg);
        }
        ifile.close();
    }

    输出:

    this is 0 file
    hello this is testing fstream!
    eof: 1
    this is 1 file
    eof: 1
    this is 2 file
    eof: 1

    可以改用rdbuf

    View Code
     1 #include<fstream>
     2 #include<iostream>
     3 #include<string>
     4 using namespace std;
     5 
     6 int main(){
     7     ofstream ofile("test.txt");
     8     ofile<<"hello this is testing fstream!";
     9     ofile<<endl;
    10     ofile.close();
    11 
    12     ifstream ifile("test.txt");
    13     string line;
    14     for(int i=0; i<3; i++){
    15         cout<<"this is "<<i<<" file"<<endl;
    16         cout<<ifile.rdbuf();
    17         cout<<"eof: "<<ifile.eof()<<endl;
    18         ifile.seekg(0,ios::beg);
    19     }
    20     ifile.close();
    21 }

    输出:

    this is 0 file
    hello this is testing fstream!
    eof: 0
    this is 1 file
    hello this is testing fstream!
    eof: 0
    this is 2 file
    hello this is testing fstream!
    eof: 0

     

  • 相关阅读:
    Qt BarChart实践
    Qt Charts_Audio实践
    Qt 报错LINK2019:无法解析的外部符号
    Qt Charts实践
    Qt Qwdget 汽车仪表知识点拆解8 淡入效果
    因果图法设计测试用例
    Jsoup获取部分页面数据失败 Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml
    loadrunner入门篇
    如何对jmeter设置IP欺骗
    jmeter录制移动端脚本
  • 原文地址:https://www.cnblogs.com/ylan2009/p/2482040.html
Copyright © 2011-2022 走看看