Jatin Jatin - 1 year ago 50
C++ Question

Keeping previous record, how to add new text in textfile using fstream in c++

In C++ I have made a program which writes given data into a text file (notepad). The problem is when I restart my program and enter other data then it clears the previous one and adds new data.

I want to keep my previous data safe, and add new data in a new line in text file.

For example,

I wrote "I am a programmer" in my program.
Now my text file will show this:

I am a programmer

Now if I restart my program and write "I am unemployed". Then textfile shows this:
I am unemployed

But I want my file to be:

I am a programmer

I am unemployed

Please, Help...

Answer Source

You need to open the file with the append flag. If you're using fstream, it looks something like this:

using namespace std;

fstream outfile = fstream("myfilename.txt", ios_base::app)

See reference http://www.cplusplus.com/reference/fstream/fstream/open/