#include #include #include #include #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"); }