#include #include #include #include static int should_exit = 0; static char buf[128]; static void do_exit(const char *s); struct cmd main_cmds[] = { { "exit", do_exit }, { "quit", do_exit }, { "flash", do_flash_cmd }, { "ftl", do_ftl_cmd }, { "mufs", do_mufs_cmd }, { NULL, NULL }, }; static void do_exit(const char *s) { (void)s; should_exit = 1; } static char *prompt(const char *prefix) { size_t len; printf(prefix); if (!fgets(buf, 128, stdin)) return NULL; len = strlen(buf); if (len > 0 && buf[len - 1] == '\n') buf[len - 1] = '\0'; putchar('\n'); return buf; } void cmd_exec(struct cmd *cmds, const char *line) { struct cmd *cmd; const char *args; char *key; size_t n; n = strcspn(line, " \n"); key = strndup(line, n); args = line + n; args += strspn(args, " \n"); for (cmd = cmds; cmd->key; ++cmd) { if (strcmp(cmd->key, key) == 0) { cmd->exec(args); break; } } free(key); } void cmd_loop(const char *show) { char *line; should_exit = 0; while (!should_exit) { line = prompt(show); cmd_exec(main_cmds, line); } }