【问题标题】:Can't append text to specific position in C++无法将文本附加到 C++ 中的特定位置
【发布时间】:2016-06-23 13:45:10
【问题描述】:

我正在尝试使用 ofstream 和 seekp 在 C++ 中将文本添加到特定位置。但是,它总是附加到文件的末尾。

我已经尝试用file.write(string, len)写信,但结果是一样的。

我的代码:

void printHistory(int media, time_t timestamp){
    ofstream file("history.json", ios::app);
    long initial_pos = file.tellp();
    file.seekp(initial_pos-3);
    file << ", [" << timestamp << "," << media << "]]\n}";
    file.close();
}

【问题讨论】:

  • 当然operator&lt;&lt;() 不关心seekp() 调用。您必须改用file.write()。但请注意:这会覆盖该位置的所有内容。
  • 我已经尝试过了。结果是一样的……
  • 请发minimal reproducible example,这样大家都能重现你的问题。
  • 我不想添加到最后。我正在尝试在末尾添加负 3,但是,程序总是在末尾追加。
  • @LuizGuilhermeFonsecaRosa 程序总是在末尾追加那是因为你用ios::app打开ofstream,which means:所有输出操作都会发生在文件末尾,附加到其现有内容。

标签: c++ string file io


【解决方案1】:

怎么样:

fstream fs ("fred.txt", ios::in | ios::out);
fs.seekg (0, ios::end);
streamoff filesize = fs.tellg();
fs.seekp (filesize - 3);    // locate yourself 3rd char from end.
fs.write( "X", 1 );
fs.close();

【讨论】:

  • 最好也说明你的代码有什么不同以及为什么,而不是只用代码给出答案而没有解释它是如何解决问题的。
  • @hyde 一般来说,我同意。
【解决方案2】:

通常,要“插入”,您必须写入临时流或文件。中途不能主动更新。

很多 STL 类型都支持插入,但它是通过幕后进程模拟的。

伪代码:

pos = some_int_point_in_file
open(file) as f and open(tmp) as t:
    read f into t until pos then
        insert whatever
    finishing reading the rest of f into t
swap file and tmp

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 2016-05-02
    • 2016-10-30
    • 2011-08-24
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多