Avoid contents of an existing file to be overwritten when writing to a file

Monkeyanator picture Monkeyanator · Nov 22, 2011 · Viewed 38.3k times · Source

I am trying to make a game that implements high scores into a .txt file. The question I have is this : when I make a statement such as:

ofstream fout("filename.txt");

Does this create a file with that name, or just look for a file with that name?

The thing is that whenever I start the program anew and make the following statement:

fout << score << endl << player; 

it overwrites my previous scores!

Is there any way for me to make it so that the new scores don't overwrite the old ones when I write to the file?

Answer

J. Calleja picture J. Calleja · Nov 22, 2011

std::ofstream creates a new file by default. You have to create the file with the append parameter.

ofstream fout("filename.txt", ios::app);