2010-11-04 225 views
0

我想知道爲什麼下面這段代碼不起作用,看起來非常直截了當,我犯了一個錯誤嗎?
這樣做的結果是:文件已創建但爲空,如果手動添加行,這些代碼會顯示這些行,但不會發生任何其他情況。使用std :: fstream讀取/追加文件

#include <fstream> 
#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 
    fstream mfile("text.txt", ios_base::in | ios_base::out | ios_base::app); 

    mfile.seekg(ios_base::beg); 
    string line; 
    while(getline(mfile,line)){ 
     std::cout << line << "\n"; 
    } 
    mfile.seekg(ios_base::end); 

    mfile << "Line 1\n"; 
    mfile << "Line 2\n"; 
    mfile << "---------------------------------\n"; 

    mfile.seekg(ios_base::beg); 
    while(getline(mfile,line)){ 
     std::cout << line << "\n"; 
    } 
    mfile.seekg(ios_base::end); 

} 
+1

是你試圖寫東西到文件?這段代碼沒有這樣做。 – birryree 2010-11-04 20:28:11

+0

什麼'mfile <<「第1行\ n」;'當mfile是fstream時呢? – 2010-11-04 20:31:15

回答

2

幾件事情:

當你準備寫,你需要seekp()而非seekg(),即

mfile.seekp(ios_base::end); 

現在,這裏的問題是,getline()通話將設置流標誌(特別是eof),並且因此流尚未準備好進行進一步的操作,您需要先清除標誌!

試試這個:

string line; 
mfile.seekg(ios_base::beg); 
while(getline(mfile,line)){ 
    std::cout << line << endl; 
} 
mfile.seekp(ios_base::end); // seekp 
mfile.clear(); // clear any flags 

mfile << "Line 1" << endl; // now we're good 
mfile << "Line 2" << endl; 
mfile << "---------------------------------" << endl; 

mfile.seekg(ios_base::beg); 
while(getline(mfile,line)){ 
    std::cout << line << endl; 
} 

此外,使用std :: ENDL而非「\ n」,這將觸發緩衝區在OS的舒適文件的紅暈......

+0

正確!旗幟是問題。 getlines之後的一個'clear()'解決了這個問題。 seekp並不是真的需要,因爲我根本沒有修改put ptr。我只是沒有意識到有一個get ptr和一個put ptr。 :d – 2010-11-04 20:35:57