这个问题在这里已有答案:
据我了解,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
在我看来,Visual Studio编译器中的问题(我使用2019版本,但@Scheff可以在VS2013中重现这种类型的错误)。
所以解决方案是在读取之后插入file.seekp(file.tellp()),反之亦然。或者你可以使用另一个编译器:-)