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?
Select the Components tab and right-click on the component name. Select Details; the Component Details dialog appears. Mark the checkbox option to "Never overwrite if keypath exists." In addition, make sure that the file is the keypath of the Component in the File Key Path field. Click OK.
You can do this with the write() method if you open the file with the "w" mode. As you can see, opening a file with the "w" mode and then writing to it replaces the existing content. 💡 Tip: The write() method returns the number of characters written.
Overwriting is the rewriting or replacing of files and other data in a computer system or database with new data. One common example of this is receiving an alert in Microsoft Word that a file with the same name already exists and being prompted to choose whether you want to restore the old file or save the new one.
std::ofstream
creates a new file by default. You have to create the file with the append parameter.
ofstream fout("filename.txt", ios::app);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With