Append to each line

Sep 18, 2010 at 11:44am
My file needs to be updated frequently, meaning that new data has to be appended, but in a very specific way. The following is the sample content of my "file.txt" (2 vectors of length 6):
1
2
3
4
5
6
1 2
3 4
5 6
7 8
3 4
5 6

After certain calculations, new vectors need to be appended to this file. Suppose v={9, 8, 7, 6 , 5, 4} is the vector to be added. The file content should be:
1
2
3
4
5
6
1 2 9
3 4 8
5 6 7
7 8 6 
3 4 5
5 6 4

Note that simple rewriting the file based on old+new vectors is not an option, and the vectors need to be 'appended' as I did. The idea is to reach the end of each line, and start appending there, then jump to next intact line, do the same thing...
This is what I've tried, but it doest work:
1
2
3
4
5
    std::fstream out;
    out.open("file.txt", std::ios::in | std::ios::out);
    std::string myHelper;
    getline(out, myHelper);
    out<<9<<std::endl;

Any suggestions? Thanks
Sep 18, 2010 at 12:27pm
Load the entire file into memory as a deque <string>.
Do your calculations, and append to each string in the deque.
Write the entire deque back to file.

Here is a useful link
http://www.cplusplus.com/forum/general/5542/#msg24475

Hope this helps.
Sep 18, 2010 at 1:43pm
If you not want to read the entire file you could trick the user.
Instead of appending a column create a new file changing the name in sequence, so every file will be a column file0 file1 file2 ... (this can be easily done with stringstream). And you will have a "header" file with info like: numbers of rows per file, numbers of columns, etc
Sep 19, 2010 at 1:14am
That's very wasteful with filesystem resources. You only need a maximum of two files: one to read and one to write. Once you have written the new file, delete the old one and rename the new one with the old one's name.

This is the other common trick to file handling, but it is trickier than just loading the file into a deque.
Topic archived. No new replies allowed.