Fstream文件正在被重写

fstream file being rewritten

本文关键字:重写 文件 Fstream      更新时间:2023-10-16

我正在编写一个输出文本文件的程序。任何时候我想写入文件,我打开它,seekp()到文件的末尾,写入它,然后关闭它。然而,似乎每次执行新的写操作时,它都会替换文件中先前存在的所有数据。

output.open("output.txt", fstream::out);
output.seekp(0, ios::end);
output << "Record " << key << " does not exist.r";
output.close();

这是正确的方式追加每写到文件的末尾吗?如果您有任何可能导致整个文件被重写的想法,我将不胜感激。

添加fstream::app标志

output.open("output.txt", fstream::out | fstream::app);

fstream::out总是覆盖文件中的数据。要追加内容,请使用模块fstream::app