-
Notifications
You must be signed in to change notification settings - Fork 0
/
soldier_system.c
80 lines (55 loc) · 1.79 KB
/
soldier_system.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
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
void print_slowly(const char* text);
void set_soldiers()
{
char *fname = "soldiers.txt";
FILE *file_pointer = fopen(fname, "w");
if(file_pointer == NULL) {
fprintf(stderr, "Cannot open '%s'... Exiting\n", fname);
exit(EXIT_FAILURE);
}
fputs("450", file_pointer);
fclose(file_pointer);
}
void change_soldiers(int soldiers_lost)
{
FILE* soldiersp;
soldiersp = fopen("soldiers.txt", "r");
char cur_soldiers[3];
fgets(cur_soldiers, 4, soldiersp);
fclose(soldiersp);
int soldiers_num = atoi(cur_soldiers);
soldiers_num -= soldiers_lost;
itoa(soldiers_num, cur_soldiers, 10);
soldiersp = fopen("soldiers.txt", "w");
fputs(cur_soldiers, soldiersp);
fclose(soldiersp);
print_slowly("\nNow we only have ");
print_slowly(cur_soldiers);
print_slowly(" remaining!\n");
}
void print_soldiers()
{
FILE* soldiersp;
soldiersp = fopen("soldiers.txt", "r");
char soldiers[3];
fgets(soldiers, 4, soldiersp);
print_slowly("(we have ");
print_slowly(soldiers);
print_slowly(" remaining)\n");
fclose(soldiersp);
}
int give_soldiers() {
char *fname = "soldiers.txt"; // make name prominent
FILE *file_pointer = fopen(fname, "rt"); // local, so use local variable
if(file_pointer == NULL) {
fprintf(stderr, "Cannot open '%s'... Exiting\n", fname);
exit(EXIT_FAILURE);
}
char str[32]; // Be generous
str[0] = '\0'; // Is a 'string' even if source file is zero length
fgets(str, sizeof str, file_pointer); // Should test for EOF condition, probably.
fclose(file_pointer);
return atoi( str ); // fgets() insures null terminated string
}