2017-10-19 18 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