tags:

views:

73

answers:

5

When saving something to a text file is there a way to not override whats in the file already?

EX.

blah.txt

this is an example

fout << "of saving to a file.";

i want the "of saving to a file" to be added on to "this is an example" not to override it.

+2  A: 

You should open the file with the appropriate write mode in order to append to it instead of overwriting:

pFile = fopen ("myfile.txt","a");

(C style), or

fstream filestr ("myfile.txt", fstream::ate | fstream::out);

(C++ style). In the latter case, you may want to use fstream::app instead of fstream::ate - this sets the file pointer to the end of the file before each output operation.

Péter Török
so instead of using fout.open(blah.txt) what should i use?
Alec
@Alec, see my update.
Péter Török
+5  A: 

use the append flag, like this:

fstream fout("blah.txt", ios::app);

if you are opening it after declaration, use something like this:

fout.open("blash.txt", fstream::app);
Gabi Purcaru
okay, this is exactly what i was looking for. Thank you!
Alec
@Alec you're welcome :) also, you could accept the answer
Gabi Purcaru
Plan on it. Have to wait 5mins
Alec
+1  A: 

Yes. You need to open the file in append mode.

ofstream fout("blah.txt", fstream::out | fstream::app);
JoshD
A: 

You need to open the file output stream in append mode:

ofstream fout(<path>, ios::app);
Andrew Stein
A: 

You can manually set the write position if you want to

u need: #include <stdio.h> ...

FILE *file = fopen("my_file.txt", "w");
fputs ("This is some text." , file);
fseek (file , 15, SEEK_SET);
fputs (" sam" ,file);
fclose (file);
UGEEN