【问题标题】:I can't write to a file right after reading it using fstream [duplicate]使用 fstream 读取文件后,我无法立即写入文件 [重复]
【发布时间】:2019-04-28 10:53:32
【问题描述】:

据我了解,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

【问题讨论】:

  • 它为我更改了文件。运行程序后Output.txt 包含a&lt;newline&gt;testd&lt;newline&gt;b&lt;newline&gt;c&lt;newline&gt;test 覆盖。
  • @TedLyngmo tellg: 3/tellp: 3 看起来好像 OP 在 Windows 上(其中行以 \r\n 结尾)。我不明白的是tellg: 9/tellp: 9file.write("test", 4); 之后。在这两种情况下,我都希望 3 + 4 = 7...
  • @Scheff 确实,它看起来确实像 Windows ...我得到了与 OP 相同的结果 :-)
  • 是的,它是 Windows,Visual Studio 2019...
  • 无法在 cygwin 中使用 g++ 重现,但 可以 使用 VS2013 重现。 (除了第二个tellg/tellp 在我的情况下报告了 12。)发现SO: How is std::fstream with both in and out supposed to work?当您在写入后执行读取或反之亦然时,应重新定位流。 这似乎给了一个提示......

标签: c++ io fstream


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多