Search code examples
c++iostreamseekg

How to append to file using seekg and seekp in c++, without using ios::app flag


I am not getting proper output while using seekp and seekg function, while on the other hand when I use ios::app for appending, program works well. How should I use seekg(), and seekp() functions for appending on a file?

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{            clrscr();

ofstream out;
out.open("MJ");
char data[100];
cout<<"\nEnter data: ";
cin.getline(data,100);
out<<data;
out.close();
ifstream in;
in.open("MJ");

in>>data;
cout<<data;

in.close();


out.open("MJ");

cout<<"\nEnter data: ";
cin.getline(data,100);
out.seekp(2);
out<<data;

out.close();

in.open("MJ");
in>>data;
cout<<data<<endl;


     getch();

}

Solution

  • When you do out.seekp(2) you only seek two bytes into the file, and then overwrite whatever is beyond that, but that's not the problem.

    The problem is is when you reopen the file the old contents is destroyed, the file is truncated. You need to open the file in open | in mode to not destroy content, if you want to manually seek to the end:

    out.open("MJ", ios::out | ios::in);
    

    It's okay to open an "output" stream in ios::in mode.

    See e.g. this reference which have a nice table of modes and what they do and mean.