我有一个我创建的游戏。我想实现一个加载和保存高分的功能。起初,当没有文本文件(在我的情况下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 似乎已经覆盖了文件中的内容并将其留空