12.积分的比较和写入

HJ Lv2

12.积分的比较和写入

读取最高积分

读取外部文件的内容,该文件保存了最高积分:

1
2
3
4
5
6
7
8
9
10
11
int getScore() {
int fileNumber = 0;
FILE* file = fopen("score.bin", "rb");
if (file != NULL) {
if (fread(&fileNumber, sizeof(int), 1, file) != 1) {
fileNumber = 0;//如果读取失败设为0
}
fclose(file);
}
return fileNumber;
}

如果读取失败重置最高分为0.然后返回最高积分。

比较积分

通过函数实现,其中int Userscore参数表示需要比较的积分。

1
2
3
4
5
6
7
8
9
10
void compearScore(int Userscore) {
int fileNumber = getScore();
if (Userscore > fileNumber) {
FILE* file = fopen("score.bin", "wb");
if (file != NULL) {
fwrite(&Userscore, sizeof(int), 1, file); // 将数字写入文件
fclose(file);
}
}
}

首先读取最高分。如果需要比较的积分大于最高积分,将需要比较的积分写入成为最高积分。

此页目录
12.积分的比较和写入