17

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Monkeyanator
  • 1,346
  • 2
  • 14
  • 29

2 Answers2

36

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

ofstream fout("filename.txt", ios::app); 
nbro
  • 15,395
  • 32
  • 113
  • 196
J. Calleja
  • 4,855
  • 2
  • 33
  • 54
14

If you simply want to append to the end of the file, you can open the file in append mode, so any writing is done at the end of the file and does not overwrite the contents of the file that previously existed:

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

If you want to overwrite a specific line of text with data instead of just tacking them onto the end with append mode, you're probably better off reading the file and parsing the data, then fixing it up (adding whatever, removing whatever, editing whatever) and writing it all back out to the file anew.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • Reading the file, parsing and writing everything back is not a good idea if your files are very large, it will obviously take a lot of computing power if your file is say, 100GB, not to mention RAM and disk read/write speeds. – Paolo Celati Feb 28 '17 at 21:12