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
|
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include "stlfile.h"
#define ARRSIZE(x) (sizeof(x)/sizeof((x)[0]))
struct command {
const char *name;
void (*func)();
};
void request_info();
void parse_file();
void cat_flag();
void list_commands();
struct command commands[] = {
{ "request", request_info },
{ "info", parse_file },
{ "cat", cat_flag },
{ "ls", list_commands },
};
const char*
ask(const char *fmtstr, ...)
{
static char linebuf[256];
va_list ap;
va_start(ap, fmtstr);
vprintf(fmtstr, ap);
va_end(ap);
fgets(linebuf, sizeof(linebuf), stdin);
return linebuf;
}
void*
die(const char *fmtstr, ...)
{
va_list ap;
va_start(ap, fmtstr);
vfprintf(stderr, fmtstr, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
void
request_info()
{
const char *bufp;
char *end, *contents;
int len;
bufp = ask("How large is your file?\n");
len = strtoul(bufp, &end, 10);
if (!len || *end || len < 7000)
die("Invalid file length!\n");
printf("Ok! Im listening..\n");
contents = malloc(len);
read(STDIN_FILENO, contents, len);
printf("I got: %s\n", contents);
free(contents);
}
void
parse_file()
{
printf("hi\n");
}
void
cat_flag()
{
FILE *f;
char catbuf[256];
int nb;
f = fopen("cat", "r");
nb = fread(catbuf, 1, sizeof(catbuf), f);
fclose(f);
printf("%.*s\n", nb, catbuf);
}
void
list_commands()
{
int i;
printf("Available commands:\n");
for (i = 0; i < ARRSIZE(commands); i++)
printf("%s%s", i ? " " : "", commands[i].name);
printf("\n");
}
int
main()
{
char linebuf[256], *cp;
int exit, i;
exit = 0;
while (!exit) {
memset(linebuf, ' ', sizeof(linebuf));
printf("$ ");
exit = !fgets(linebuf, sizeof(linebuf), stdin);
if (exit || !*linebuf) break;
if (*linebuf == '\n') continue;
linebuf[strlen(linebuf) - 1] = '\0';
cp = strchr(linebuf, ' ');
if (cp) *cp = 0;
for (i = 0; i < ARRSIZE(commands); i++) {
if (!strcmp(commands[i].name, linebuf)) {
commands[i].func();
break;
}
}
}
printf("see you later!\n");
}
|