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
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 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:

std::fstream out;
    out.open("file.txt", std::ios::in | std::ios::out);
    std::string myHelper;
    getline(out, myHelper);

Any suggestions? Thanks

7 Years
Discussion Span
Last Post by onako

Of course it doesn't work.

Since you can't rewrite the file, the only thing I can suggest is when the file is originally written pad each line with spaces at the end to make room for the new data. So instead of

"1 2"

you would have written

"1 2             "

Then you could do something like this:

int main()
    std::string line;
    size_t offset = 0;
    std::fstream out;
    out.open("TextFile.txt", std::ios::in | std::ios::out);
    // add 9 to the first white space in the second line
    if( !out.is_open() )
        std::cout << "Error opening the file\n";
        return 1;
    // read the first line
    // get the offset to the beginning of the line that 
    // I need to rewrite
    offset = (size_t)out.tellg();
    // read the line that needs to be updated
    // find the position of the last space in the line
    size_t pos = line.find("  ");
    line[pos+1] = '9';  
    // back to the beginning of the line that 
    // needs to be updated
    // rewrite the entire line
    out << line;

Edited by Ancient Dragon: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.