Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

ofstream

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?

like image 259
Monkeyanator Avatar asked Nov 21 '11 23:11

Monkeyanator


People also ask

How do you stop a file from being overwritten?

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.

Which mode would you select to write data to a file without losing its existing content?

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.

What does it mean to overwrite an existing file?

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.


2 Answers

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

ofstream fout("filename.txt", ios::app); 
like image 94
J. Calleja Avatar answered Oct 20 '22 13:10

J. Calleja


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.

like image 41
Seth Carnegie Avatar answered Oct 20 '22 11:10

Seth Carnegie