-
Notifications
You must be signed in to change notification settings - Fork 0
/
highscore.c
52 lines (48 loc) · 1.18 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
#include "highscore.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *get_highscore_path() {
int len;
char *homepath, *highscorepath;
homepath = getenv("HOME");
len = strlen(homepath) + strlen("/.ttytris_highscores");
highscorepath = malloc((len + 1) * sizeof(char));
sprintf(highscorepath, "%s/.ttytris_highscores", homepath);
return highscorepath;
}
int read_highscores(int *highscores) {
int i;
char *path;
FILE *hsfile;
path = get_highscore_path();
hsfile = fopen(path, "r");
if (hsfile == NULL)
return 0;
for (i = 0; i < NHIGHSCORES; i++) {
if (fscanf(hsfile, "%d", &highscores[i]) == EOF)
break;
}
free(path);
fclose(hsfile);
return i;
}
void save_highscore(int score) {
char *path;
int i, nhighscores, highscores[NHIGHSCORES];
FILE *hsfile;
nhighscores = read_highscores(highscores);
path = get_highscore_path();
hsfile = fopen(path, "w");
for (i = 0; i < nhighscores && highscores[i] < score; i++) {
fprintf(hsfile, "%d\n", highscores[i]);
}
if (i < NHIGHSCORES) {
fprintf(hsfile, "%d\n", score);
for (; i < NHIGHSCORES - 1 && i < nhighscores; i++) {
fprintf(hsfile, "%d\n", highscores[i]);
}
}
free(path);
fclose(hsfile);
}