Monkeyanator Monkeyanator - 1 month ago 9
C++ Question

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

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

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

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