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

标签 c++ text text-files fstream

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

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

}

我怎样才能做到:

如果文件存在,则应打开以供读取

否则应创建文件

谢谢你的时间

最佳答案

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

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

如果您使用 ifstreams 和 ofstreams,则不需要特殊标志,也不需要在文件中查找 - 您只需重写整个内容即可。

关于c++ - 初学者 C++ - 打开一个文本文件进行阅读,如果它存在,如果不存在,则将其创建为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2834566/

相关文章:

c++ - 包含多个 OpenCL 内核的程序与每个包含一个内核的多个程序相比有何优势?

c++ - CMake目录层次结构,独立构建子目录

c++ - 如何用cpp中的 map 内容覆盖文件

c# - 如何在应用程序关闭之前写入文本文件

c++ - 如何在 LLVM IR 中获取字符串文字的值?

C# 如何在文本文件中写入多行?

Swift:混合风格的文本

javascript - PHP 保存文本文件并随后在另一个页面上显示它并不每次都有效

c - 从文件中读取可变长度数组

c++ - 如何从文本文件中删除特定点之前的所有行和单词