簡體   English   中英

fstream,先寫,再讀,再寫,最后寫失敗,不知道是什么原因

[英]fstream, to write ,then read, then write, but last write is failed,i don't know the reason

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”。 我不知道原因,請幫助我。

流狀態的 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM