hi I am trying to write into a file which already has something in it.
like for example i have
x
y
z
in the file and if i want to put k after x,y and z like
x
y
z
k.

my code goes this way

int main () {
  //string line;
  ofstream myfile;  
  int i=0;
  myfile.open ("example2.txt");
  myfile.seekp (0, ios::end); 
  while(myfile.eof()){
  }  
  myfile << "Writing this to a file.\n";    
  myfile.close();  
  return 0;
}

everytime i am compiling this program its creating a new example2 text file, but i want the output to be added to the existing lines in the text file.could anyone tell how i can do it..

The default to open() is to truncate the existing file and start anew. To append to the file add the ios::app flag. myfile.open ("example2.txt", ios::app); Read this for a complete list of the flags you can use in open()

hi buddy,
thank you for replying....i actually used a fstream and manipulated by going to end of file by using seekg to get to the end and it actually worked..here is the code

string line;
fstream myfile2;
myfile2.open ("example2.txt");
while( myfile2.eof()){
getline(myfile2,line);
cout << line << endl;
}
myfile2.seekg (0, ios::end);
myfile2 << "Writing this to a file.\n";
myfile2.close();

...thanks again for replying...

Edited 3 Years Ago by happygeek: fixed formatting

This article has been dead for over six months. Start a new discussion instead.