1. 程式人生 > >【C/C++開發】C++檔案流關於seekg失效的問題

【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