fstream,写,然后读,然后写,但最后写失败,我不知道原因

时间:2017-10-19 06:57:54

标签: c++

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内容是&#34; 45464748&#34;但我应该理解它的内容是&#34; 1094861636&#34;。我不是原因,请帮助我。

1 个答案:

答案 0 :(得分: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