【C/C++开发】C++文件流关于seekg失效的问题

关于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

复制代码
 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值