2017-10-19 19 views
1
fstream fs("f.txt", fstream::in | fstream::out | fstream::trunc); 
if(fs) 
{ 
    string str = "45464748"; 
    fs << str; 

    fs.seekg(0, ios::beg); 

    int i = -1; 
    fs >> i; 
    cout << i << endl; 

    fs.seekp(0, ios::beg); 

    i = 0x41424344; 
    fs << i; 

    fs.close(); 
} 

f.txt內容是「45464748」,但我應該瞭解它的內容是「1094861636 」。我沒有理由,請幫助我。fstream的,寫,然後讀,然後寫,但最後寫入失敗,我不知道原因

+0

是否'COUT <<我<< ENDL;''打印45464748'? – SgtDroelf

+0

是的,但接下來寫入失敗 –

+1

哪個編譯器?哪個標準(C++ 11,C++ 14,...)?你能否在不同的地方檢查不同的位(eofbit,failbit,badbit)? –

回答

1

流狀態的eof位由前一次讀取設置,所以寫入無效。寫之前清除流狀態。

void ftest() 
{ 
    std::fstream fs("f.txt", std::fstream::in | std::fstream::out | std::fstream::trunc); 
    if(fs) 
    { 
    std::cout << "A: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    std::string str = "45464748"; 
    fs << str; 
    std::cout << "B: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    fs.seekg(0, std::ios::beg); 
    std::cout << "C: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    int i = -1; 

    // THIS read sets the EOF bit. 
    fs >> i; 

    std::cout << "D: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    std::cout << i << std::endl; 
    fs.seekp(0, std::ios::beg); 
    std::cout << "E: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    i = 0x41424344; 
    std::cout << "F: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    fs << "not written"; 
    fs.clear(); 
    std::cout << "G: " << (fs.eof() ? "eof" : "neof") << std::endl; 
    fs << i; 
    fs.close(); 
    } 
} 

輸出:

A: neof 
B: neof 
C: neof 
D: eof 
45464748 
E: eof 
F: eof 
G: neof 

文件內容:

1094861636 
+0

http://www.cplusplus.com/reference/ostream/ostream/seekp/說:「請注意,即使在調用之前設置了eofbit標誌,該函數仍然可以工作,但它不會修改它。」而且我不明白爲什麼寫在文件末尾會失敗!? –

+0

如果你願意,你可以在clear之前做seekp,它會起作用,正如你引用的文檔所說的那樣。但寫不起作用。它失敗的原因是這些規則 - 請參閱文檔ostream :: put然後ostream :: sentry。 – Buster