【问题标题】:How to go to the beginning of the file in fstream? [duplicate]如何在 fstream 中转到文件的开头? [复制]
【发布时间】:2018-10-25 20:18:40
【问题描述】:

我正在练习文件处理。我制作了一个文本文件并在其中写入了一些字符,现在我希望光标转到文件的开头并使用 seekp 将一个字符放在那里。

这里是代码

fstream ofile;

char ch = 'g';

ofile.open("test.txt", ios::out | ios::app);

ofile.seekp(0, ios::beg);
ofile.put(ch);

ofile.close();

预期结果: 它在文件开头写 g。

实际结果: 它在末尾附加 g。

我尝试删除 ios::app 标记,但 ios::out 单独在写入任何内容之前会截断文件。

【问题讨论】:

标签: c++ file-handling


【解决方案1】:

见: http://en.cppreference.com/w/cpp/io/basic_fstream/open

std::ios::app seek to the end of stream before each write

【讨论】:

    猜你喜欢
    • 2022-06-29
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2018-01-04
    • 1970-01-01
    相关资源
    最近更新 更多