#include #include #include #include struct cmd main_cmds[] = { { "flash", do_flash_cmd }, { "ftl", do_ftl_cmd }, { "mufs", do_mufs_cmd }, { NULL, NULL }, }; static char *prompt(const char *prefix) { char *alloc, *line; size_t nbytes = 0, nalloc_bytes = 16; char c; printf(prefix); if (!(line = malloc(nalloc_bytes))) return NULL; while ((c = getchar()) && c != '\n') { if (nbytes + 1 >= nalloc_bytes) { nalloc_bytes *= 2; if (!(alloc = realloc(line, nalloc_bytes))) goto err_free_line; line = alloc; } line[nbytes++] = c; } line[nbytes] = '\0'; return line; err_free_line: free(line); return NULL; } 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); return; } } } void cmd_loop(const char *show) { char *line; while (1) { line = prompt(show); cmd_exec(main_cmds, line); free(line); } }