【问题标题】:Loading and Saving from a file c++ highscore function从文件加载和保存 c++ 高分函数
【发布时间】:2012-04-29 12:33:31
【问题描述】:

我创建了一个游戏。我想实现一个加载和保存高分的功能。起初,当没有文本文件时(在我的情况下为highscore.txt),一旦创建,我想将 0 打印到文件中。如果它在加载中,我希望它加载之前玩游戏的高分。我该怎么办?

这是我的代码:

void filewrite(){

    int n;

    FILE *FPtr;
    FPtr = fopen("highscore.txt","w+");//open file
    if (FPtr == NULL){
    fprintf (FPtr, "%d" , highscore);
    rewind(FPtr);
    }
    fscanf(FPtr,"%d",&n);//scan file for integer


    if (n < score){
        if(highscore < score ){
            if(end==true){
                fprintf (FPtr, "%d" , score);//print the score to file if it is higher than the score already there
                rewind(FPtr);//rewind the file, so pointer starts at begining
                fscanf(FPtr,"%d",&highscore);//scan file for int
            }
        }
    }

    fclose(FPtr);//close pointer to file

}

fopen 似乎已经覆盖了文件中的内容并将其留空

【问题讨论】:

  • 这在我看来更像 C。还有,问题是什么?
  • 您可能希望将条件 if (FPtr == NULL) 更改为 if (FPtr != NULL)。现在,实际的问题和疑问是什么?

标签: c++


【解决方案1】:

您应该采取的步骤是:

  • 尝试打开文件进行阅读。
  • 如果失败,则打开写入,写入 0,然后打开读取。
  • 读取文件中的值并根据需要进行测试。

【讨论】:

  • 或者:* 尝试读取文件。如果它不存在,则假装它包含 0。 * 将读取的值与新分数进行比较。 * 如果新分数更高,则将其写入文件。 (如果有人得分为 0,则不会创建文件,但最终结果是相同的。)
  • 干杯,做这个太久了,所以你没有想到的简单的事情。欣赏它:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 2020-02-26
  • 2016-12-22
相关资源
最近更新 更多