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);
    out<<9<<std::endl;

Any suggestions? Thanks

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
    std::getline(out,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
    std::getline(out,line);
    // 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
    out.seekg(offset,std::ios::beg);
    // rewrite the entire line
    out << line;
    out.close();
}

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.