C++ append to existing file

1.2k views Asked by At

I'm trying to take data from multiple files and append them into one file using fstream, however whenever I try to output to an existing file using

 std::ofstream Out("mushroom.csv", std::ofstream::app);

it outputs to the end of the file, I want it to append to the same line, for example if this is the previous file:

 1,2,3,4,5,6,7
 8,9,10,11,12,13

I want it to become:

 1,2,3,4,5,6,7,a,b,c
 8,9,10,11,12,13,c,d,e
1

There are 1 answers

0
NathanOliver On BEST ANSWER

You can't. Files don't really have lines, they just store a bunch of characters/binary data. When you have

1,2,3,4,5
6,7,8,9,0

It only looks that was because there is an invisible character in there that tells it to write the second line to the second line. The actual data in the file is

1,2,3,4,5\n6,7,8,9,0

So you can see then end of the file is after the 0 and to get after the 5 you would need to seek into the middle of the file.

The way you can get around this is to read each line of the file into some container and then add your data to the end of each line. Then you would write that whole thing back o the file replacing the original contents.