简体   繁体   中英

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. Probably, a good idea would be to move back the cursor to skip the '\n' character in the existing file. 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" is for "append", which does not mean "write in an arbitrary location".)

You want ate (one of the more inscrutable names in C++) which seeks to the end only immediately after opening.
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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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