-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.c
61 lines (41 loc) · 1 KB
/
file.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
#include "head.h"
void add_winner(PLAYER * winner){
int i = 0, j = 0;
char leader_file[32] = "leader_board_", s_size[3];
sprintf(s_size, "%d", winner->size);
strcat(leader_file, s_size);
PLAYER ** leaders = load(leader_file);
PLAYER ** lasts = load("recent_players");
for (i = 9; i > 0; i--){
lasts[i] = lasts[i - 1];
}
lasts[0] = winner;
while (i < 10 && player_gt(leaders[i], winner))
i++;
if (i < 10){
for (j = 9; j > i; j--)
leaders[j] = leaders[j - 1];
leaders[j] = winner;
}
save(leader_file, leaders);
save("recent_players", lasts);
free(leaders);
free(lasts);
}
void save(char file_name[32], PLAYER ** players){
FILE * file = fopen(file_name, "wb");
if (file){
fwrite(players, sizeof(PLAYER *), 10, file);
fclose(file);
}
}
PLAYER ** load(char file_name[32]){
FILE * file = fopen(file_name, "ab+");
PLAYER ** players;
players = malloc(10 * sizeof(PLAYER *));
if (file){
fread(players, sizeof(PLAYER *), 10, file);
fclose(file);
}
return players;
}