-
Notifications
You must be signed in to change notification settings - Fork 1
/
interactive.c
69 lines (57 loc) · 1.1 KB
/
interactive.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
#include <stdio.h>
#include <string.h>
#define PROMPT "TEST> "
static char *getcmd(void)
{
// output the promption
fputs(PROMPT, stdout);
fflush(stdout);
// get command input
char line[256];
char *r = fgets(line, sizeof(line), stdin);
if (!r)
return NULL;
// trim tailling newline
if (r[strlen(r) - 1] == '\n')
r[strlen(r) - 1] = 0;
return strdup(r);
}
static void usage()
{
fprintf(stderr,
"Usage: ./a.out\n"
"A simple interactive command line interface\n"
"\n"
"COMMAND:\n"
" ? | help This help message.\n"
" quit | exit Say byebye.\n"
);
}
static void run_command(const char *cmd)
{
printf("Run command [%s] with\n", cmd);
int i = 1;
char *arg = strtok(NULL, "\t ");
while (arg) {
printf("ARG#%d = [%s]\n", i, arg);
arg = strtok(NULL, "\t ");
i++;
}
}
int main()
{
while (1) {
char *cmdstr = getcmd();
char *cmd = strtok(cmdstr, "\t ");
if (!cmd || cmd[0] == '?' || !strcasecmp(cmd, "help")) {
usage();
continue;
}
if (!strcasecmp(cmd, "quit") || !strcasecmp(cmd, "exit")) {
printf("Bye!\n");
break;
}
run_command(cmd);
}
return 0;
}