Why do seekp/tellp behave differently in append mode?

Viewed 97

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 \t4to the existing line that works both simple open and in append mode?

Edit: based on the helpful comments below, changing the second file opening to

outfile.open("outfile.dat", std::ios::ate | std::ios::in);

appears to solve the problem. ate seeks to the end of the file only at opening as opposed to app which indeed seeks to the end after each write operation. The output now is

$ cat outfile.dat 
1   2   3   4
1   2   3   4
0 Answers
Related