初学者C++ - 打开一个文本文件进行读取(如果不存在),如果不存在,则将其创建为空

F. *_* P. 3 c++ text fstream text-files

我正在为基于文本的游戏编写一个高分子例程.这是我到目前为止所拥有的.

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();

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能这样做:

如果文件存在,它应该是开放的阅读

ELSE文件应该被创建

谢谢你的时间

小智 5

我会说错误的逻辑.我想你想要:

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
Run Code Online (Sandbox Code Playgroud)

如果您使用ifstreams和ofstreams,则不需要特殊标志,或者可能需要在文件中搜索 - 您只需重写整个内容.