使用 std::ofstream 仅重写前 30 个字符的方法

Way to rewrite only first 30 chars using std::ofstream?

本文关键字:字符 方法 重写 std ofstream 使用      更新时间:2023-10-16

有没有办法使用 std::ofstream 只重写文本文件的前 30 个字符,而不清除文本文件的所有其他内容?我在网上看了一下,但这没有帮助。一个人提出重写整个文件,但这非常低效(还有其他+900 * 30个字符)。任何人?哦,这是我的代码:

void Unlock(int Level)
{
    ifstream CheckIfExists("levels.txt");
    if (!CheckIfExists.good())
    {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "ERROR",
                                 "Unable to open the levels file. Next level won't be unlocked!", window);
        CheckIfExists.close();
        return;
    }
    CheckIfExists.close();
    if(Level >= 0 && Level <= 29)
    {
        ofstream New_Locks("levels.txt");
        Locked[Level] = UNLOCKED;
        for(int i = 0; i < 30; ++i) New_Locks << Locked[i];
        New_Locks.close();
        return;
    }
    else SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Congratulations!",
                                  "You won! Thank you for playing! Maybe once more?", window);
    return;
}

使用 fstream 而不是 ofstream

ifstream仅用于阅读,ofstream仅用于写作,fstream两者兼而有之。

另请注意:没有必要显式关闭文件。流析构函数将正确关闭它们。