我正在尝试使用ofstream
和seekp
在C ++中将文字添加到特定位置。但是,它总是附加到文件的末尾。
我 alredy尝试用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();
}
答案 0 :(得分:0)
通常,要“插入”,您必须写入临时流或文件。你无法在中间积极更新。
许多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
答案 1 :(得分:0)
如下:
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();