Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to a File with fstream Instead of Overwriting

I'm trying to create a basic highscore system for a project I'm working on.

The problem I'm having is, although I write the names into my main they just overwrite the previous.

Currently I have this:

void ManagePoint::saveScore(string Name, int Score) {      ofstream newFile("scorefile.txt");      if(newFile.is_open())        {         newFile << Name << " " << Score;                 }     else      {         //You're in trouble now Mr!     }       newFile.close();  } 

and for testing I'm adding them like so:

runner->saveScore("Robert", 34322);  runner->saveScore("Paul", 526);  runner->saveScore("Maxim", 34322); 

On load display all that will appear is Maxim's score, how can I loop through and save them all, or append all or something?

like image 224
Springfox Avatar asked Feb 24 '13 20:02

Springfox


People also ask

Does fstream overwrite?

Using ofstream with the "current file" name as parameter for the constructor will overwrite it.

Does fstream create a file if it doesn't exist?

Usually, every mode that entails writing to the file is meant to create a new file if the given filename does not exist. Thus, we need to call the open built-in function of std::fstream to create a new file with the name provided as the first string argument.

Do you have to close fstream C++?

fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient. In particular, it's not a “best practice” and it's not necessary to flush the output.


1 Answers

You need to open the file with the append mode:

ofstream newFile("scorefile.txt", std::ios_base::app); 

There are various other modes too.

like image 185
Joseph Mansfield Avatar answered Sep 21 '22 12:09

Joseph Mansfield