-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.c
137 lines (119 loc) · 2.98 KB
/
2.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 0x100
#define MOTD_COUNT 3
const char default_motd[] = "<no message of the day set>\n";
int done = 0;
typedef struct motd_
{
char* motd;
int64_t rating ;
} motd_t;
void clean_stdin()
{
while (1)
{
char c = getchar();
if (c == '\n') break;
if (c == EOF) exit(1);
}
}
int getnum()
{
int choice = ~0;
scanf("%d", &choice);
clean_stdin();
return choice;
}
motd_t* get_motd(motd_t* motds)
{
printf("=> Which message of the day? (1-%d)\n> ", MOTD_COUNT);
int idx = getnum();
if (idx > MOTD_COUNT)
{
printf("This is not a valid index!\n");
return NULL;
}
return (motds + (idx-1));
}
void read_motd(motd_t* motds) {
motd_t* motd = get_motd(motds);
if (!motd) return;
printf("=> Type in the new message of the day please:\n> ");
char buf[SIZE] = {0};
// [bill] james said gets was dangerous. I think he's overreacting, but I fixed it to make the
// auditor happy.
fgets(buf, SIZE, stdin);
memcpy(motd->motd, buf, SIZE);
}
void show_motd(motd_t* motds) {
motd_t* motd = get_motd(motds);
if (!motd) return;
printf("=> %s Rated %d out of 10\n", motd->motd, motd->rating);
}
void rate_motd(motd_t* motds) {
motd_t* motd = get_motd(motds);
if (!motd) return;
printf("=> %s Rating? (out of 10)\n> ", motd->motd);
int rating = getnum();
motd->rating = rating;
printf("Thank you! Your opinion matters to us.\n");
}
void init(motd_t* motds)
{
for (int i = 0; i < MOTD_COUNT; ++i)
{
motd_t* m = motds + i;
m->rating = 0;
m->motd = (char*)malloc(SIZE);
memset(m->motd, 0, SIZE);
memcpy(m->motd, default_motd, sizeof(default_motd));
}
}
void main()
{
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stdin, NULL, _IONBF, 0);
motd_t motds[3];
init(motds);
printf("motd daemon v0.2 (c) 2019 BetterSoft\n");
fflush(stdout);
system("date"); // [bill] This is easier than manipulating time and makes our code cleaner.
while (!done)
{
printf("\n");
printf("=> How may I help you today?\n");
printf(" 1 - View message of the day\n");
printf(" 2 - Change message of the day\n");
printf(" 3 - Rate message of the day\n");
printf(" 4 - Exit\n");
printf("> ");
int choice = getnum();
printf("\n");
switch (choice)
{
case 1:
show_motd(motds);
break;
case 2:
{
read_motd(motds);
break;
}
case 3:
{
rate_motd(motds);
break;
}
case 4:
done = 1;
break;
default:
printf("I don't recognize that option.\n");
break;
}
}
printf("Bye!\n");
}