Beginner C ++ - open a text file for reading, if it exists, if not, create it empty

I am writing a subtitle with a high score for a text game. Here is what I still have.

void Game::loadHiScores(string filename)
{
    fstream hiscores(filename.c_str()); // what flags are needed?
    int score;
    string name;
    Score temp;

    if (hiscores.is_open())
    {
        for (size_t i = 0; i < TOTAL_HISCORES && !(hiscores.eof()); ++i)
        {
            cin >> score >> name;
            temp.addPoints(score);
            temp.scoreSetName(name);
            hiScores.push_back(temp);
        }
    }
    else
    {
        //what should go here?
    }   

    hiscores.close();

}

How can I do it like this:

If the file exists, it must be open for reading.

ELSE file must be created

thank you for your time

+3
source share
1 answer

Wrong logic, I would say. I think you want:

Try to open an ifstream (not an fstream) containing scores
if it opened
   read high scores into array
   close stream
else
   set array to zero
endif

Play Game - adjust high scores in array, then on exit

Try to open scores ofstream (not an fstream) for writing
if it opened
    write high scores
    close stream
else
    report an error
end if

If you use ifstream and streamstream, there is no need for special flags or, perhaps, a search in the file - you just rewrite all of this.

+5
source

Source: https://habr.com/ru/post/1745450/


All Articles