-
Notifications
You must be signed in to change notification settings - Fork 1
/
highscore.c
67 lines (55 loc) · 1.55 KB
/
highscore.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "highscore.h"
#include "debug.h"
#include "util.h"
#include <stdio.h> // fopen
#include <stdlib.h> // atoi
#include <errno.h> // errno
#include <string.h> //strerror, strlen
unsigned int highscore_init()
{
FILE* highscore_file = fopen(HIGHSCORE_FILE, "r");
if (highscore_file == NULL)
{
LOG("Error opening highscore file %s: %s\n",
HIGHSCORE_FILE, strerror(errno));
return 0;
}
char buffer[64];
int n = fread(buffer, sizeof(char), sizeof(buffer), highscore_file);
if (n <= 0)
{
LOG("Error reading highscore file %s: %s\n",
HIGHSCORE_FILE, strerror(errno));
return 0;
}
int highscore = atoi(buffer);
if (highscore < 0)
highscore = 0;
fclose(highscore_file);
return highscore;
}
void highscore_update(unsigned int highscore)
{
// Read highscore again to make sure we're not
// overwriting a higher score.
unsigned int old_score = highscore_init();
if (highscore <= old_score)
return;
FILE* highscore_file = fopen(HIGHSCORE_FILE, "w");
if (highscore_file == NULL)
{
LOG("Error opening highscore file %s: %s\n",
HIGHSCORE_FILE, strerror(errno));
return;
}
char buffer[64];
util_itoa(highscore, buffer, sizeof(buffer));
int n = fwrite(buffer, sizeof(char), strlen(buffer), highscore_file);
if (n <= 0)
{
LOG("Error writing highscore file %s: %s\n",
HIGHSCORE_FILE, strerror(errno));
return;
}
fclose(highscore_file);
}