I need to append a line to an existing file and then add one more value to that line. I'm making use of the seekp
and tellp
functions for that. Consider the following code:
#include <iostream>
#include <stdlib.h>
#include <fstream>
int main(){
//file position
long long opos;
//output file
std::ofstream outfile;
//open new file
outfile.open("outfile.dat");
outfile<<"1\t2\t3"<<std::endl;
opos = outfile.tellp();
outfile.seekp (opos-1);
outfile<< "\t4" <<std::endl;
outfile.close();
//appending existing file
outfile.open("outfile.dat", std::ios::app);
outfile<<"1\t2\t3"<<std::endl;
opos = outfile.tellp();
outfile.seekp (opos-1);
outfile<< "\t4" <<std::endl;
outfile.close();
}
It consists of two blocks. First, I open a new file, write the line 1 2 3\n
to it, then go back one step and overwrite the \n
with \t4
. This works. However, when I open the file in append mode (second block), it appears that seekp
lost track of the position. This is the output:
$ cat outfile.dat
1 2 3 4
1 2 3
4
My question is whether this is the expected behavior and if it is, how to properly add the extra value \t4
to the existing line that works both simple open and in append mode?
Aucun commentaire:
Enregistrer un commentaire