简体   繁体   English

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

[英]How to append to the last line of a file in c++?

using g++, I want to append some data to the last line (but to not create a new line) of a file.使用 g++,我想将一些数据附加到文件的最后一行(但不创建新行)。 Probably, a good idea would be to move back the cursor to skip the '\n' character in the existing file.可能,一个好主意是向后移动光标以跳过现有文件中的 '\n' 字符。 However this code does not work:但是此代码不起作用:

#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;
}

Please give me the idea of correcting the code.请给我更正代码的想法。 Thank you in advance.先感谢您。 Marek.马雷克。

When you open with app , writing always writes at the end, regardless of what tellp tells you.当你用app打开时,不管tellp告诉你什么,写作总是写在最后。
("app" is for "append", which does not mean "write in an arbitrary location".) (“app”是“append”,不代表“写在任意位置”。)

You want ate (one of the more inscrutable names in C++) which seeks to the end only immediately after opening.ate (C++ 中更难以理解的名字之一),它只在打开后立即结束。
You also want to add that final newline, if you want to keep it.如果您想保留它,您还想添加最后的换行符。
And you probably also want to check that the last character is a newline before overwriting it.而且您可能还想在覆盖它之前检查最后一个字符是否为换行符。
And , seeking by characters can do strange things in text mode, and if you open in binary mode you need to worry about the platforms's newline convention.并且,在文本模式下按字符搜索会做一些奇怪的事情如果你以二进制模式打开,你需要担心平台的换行约定。

Manipulating text is much harder than you think.处理文本比您想象的要困难得多。

(And by the way, you don't need to specify out on an ofstream - the "o" in "ofstream" takes care of that.) (顺便说一句,您不需要在ofstream上指定out - “ofstream” 中的 “o” 负责处理。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM