流状态的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)? –