流狀態的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
是否'COUT <<我<< ENDL;''打印45464748'? – SgtDroelf
是的,但接下來寫入失敗 –
哪個編譯器?哪個標準(C++ 11,C++ 14,...)?你能否在不同的地方檢查不同的位(eofbit,failbit,badbit)? –