我无法使用fstream读取文件后立即向其写入内容。

3
据我所知,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;
}

So I have a file:

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
它替我改变了文件。运行程序后,Output.txt 文件包含 a<换行>testd<换行>b<换行>c<换行>test 覆盖了。 - undefined
1
@TedLyngmo tellg: 3/tellp: 3 看起来像是 OP 在使用 Windows(其中行以 \r\n 结尾)。但我不明白在 file.write("test", 4); 后面的 tellg: 9/tellp: 9。根据我的理解,两种情况下应该是 3 + 4 = 7... - undefined
是的,它是Windows操作系统,使用的是Visual Studio 2019开发工具... - undefined
哇,我用MinGW编译器编译了同样的程序,它居然成功了!看起来问题出在VStudio编译器上。 - undefined
1
在cygwin中,使用g++无法重现,但是可以在VS2013中重现。(除了第二个tellg/tellp在我的情况下报告为12。)在SO: How is std::fstream with both in and out supposed to work?中找到了一个线索:“当你在写入或读取之后执行另一种操作时,流应该重新定位回去。” - undefined
显示剩余8条评论
1个回答

1

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

所以解决方案是在读取后的写入之前插入file.seekp(file.tellp()),反之亦然。 或者你可以使用另一个编译器:-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接