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

Recommended Answers

All 3 Replies

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

> i want the output to be added to the existing lines in the text file
> 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..
you must be using a fairly old version of the standard library. using ios::app is the easiest way, but if you must seek, use a seekp (not seekg)
see: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#136

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.