c++ - 使用 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
解决方案
在我看来,Visual Studio 编译器中的问题(我使用的是 2019 版本,但 @Scheff 可以在 VS2013 中重现这种错误)。
所以解决方案是在读取后写入之前插入一个 file.seekp(file.tellp()),反之亦然。或者你可以只使用另一个编译器:-)
推荐阅读
- python - ValueError: int() 以 10 为底的无效文字:'Pending'
- chatbot - Botium 核心 - 频繁测试失败并显示消息“AllInstitutions_3/Line 7: error sent to bot Error”
- php - 我的 sql 插入查询没有错误,但没有向数据库中插入任何内容
- react-native - ScrollView 中包裹的多个 FlatList
- scala - 将列表的 spark DF 列拆分为单独的列
- python - 根据 xy 坐标计算行和列,TypeError: 'float' object is not subscriptable
- spring-boot - 来自 Google Kubernetes Engine 的邮件
- spring-boot - @Value("${server.address}") 返回 null
- amazon-cloudformation - 我们可以在 cloudformation 模板中添加任何带有 !Ref 的字符串吗?
- ansible - 在ansible中如何禁用单个任务的弃用警告?