使用fstream读取文件后,我无法立即写入文件

时间:2019-04-28 10:53:33

标签: c++ io fstream

据我了解,fstream允许您写入和读取相同的打开文件。 它还有两个“文件指针”,一个用于读取,另一个用于写入。 但是,如果我先从文件中读取一行,然后尝试写入该文件-即使以后使用 flush(),文件也不会更改。

有一种解决方法-使用 seekp()并将“文件指针”移动到某处。 但是我不明白为什么会这样工作。 而且还有一些奇怪的细节-如果在写入前后使用 tellp()检查文件指针,它们实际上会改变位置! 也许我在某些方面弄错了,我将不胜感激

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    fstream file("Output.txt");
    string line = "";

    getline(file, line);
    cout << "Read line: " << line << endl;

    cout << "tellg: " << file.tellg() << endl;
    cout << "tellp: " << file.tellp() << endl;
    cout << "rdstate: " << file.rdstate() << endl;
    cout << "------------------------------- " << endl;

    file.write("test", 4);
    file.flush();
    cout << "After writing:\nrdstate: " << file.rdstate() << endl;
    cout << "tellg: " << file.tellg() << endl;
    cout << "tellp: " << file.tellp() << endl;

    file.close();
    cout << "------------------------------- " << endl;
    cout << "After closing:\nrdstate: " << file.rdstate() << endl;
}

所以我有一个文件:

a
b
c
d

程序运行后它没有改变。根据 rdstate()

,没有任何错误

程序输出:

Read line: a
tellg: 3
tellp: 3
rdstate: 0

After writing:
rdstate: 0
tellg: 9
tellp: 9

After closing:
rdstate: 0

1 个答案:

答案 0 :(得分:0)

在我看来,Visual Studio编译器中的问题(我使用的是2019版,但是@Scheff可以在VS2013中重现此错误)。

因此,解决方案是在读取后写入之前插入file.seekp(file.tellp()),反之亦然。 或者,您也可以使用其他编译器:-)