如何在c++中追加到文件的最后一行?



使用g++,我想将一些数据附加到文件的最后一行(但不创建新行)。也许,一个好主意是向后移动光标以跳过现有文件中的'n'字符。然而,这段代码不起作用:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream myfile;
myfile.open ("file.dat", fstream::app|fstream::out);
myfile.seekp(-1,myfile.ios::end); //I believe, I am just before the last 'n' now
cout << myfile.tellp() << endl; //indicates the position set above correctly
myfile << "just added"; //places the text IN A NEW LINE :(
//myfile.write("just added",10); //also, does not work correctly
myfile.close();
return 0;
}

请给我改正代码的想法。提前谢谢你。Marek .

当您以app打开时,无论tellp告诉您什么,writing总是在最后写入。
("app"是用于"追加",这并不意味着"在任意位置写入"。)

您想要ate(c++中更难以理解的名称之一),它只在打开后立即寻求结束。
如果您想保留它,还需要添加最后的换行符。
您可能还想检查最后一个字符在覆盖它之前是否为换行符。
,按字符查找在文本模式下会做一些奇怪的事情,如果你在二进制模式下打开,你需要担心平台的换行约定。

操作文本比你想象的要困难得多。

(顺便说一下,您不需要在ofstream上指定out- "o"在"ofstream")

最新更新