shell: simplify prompt()

tags/0.1.0
S.J.R. van Schaik 8 years ago
parent e4d0dc3cb3
commit 2b2827eb18
  1. 30
      source/shell/cmd.c

@ -5,6 +5,7 @@
#include <shell.h>
static int should_exit = 0;
static char buf[128];
static void do_exit(const char *s);
struct cmd main_cmds[] = {
@ -25,35 +26,21 @@ static void do_exit(const char *s)
static char *prompt(const char *prefix)
{
char *alloc, *line;
size_t nbytes = 0, nalloc_bytes = 16;
char c;
size_t len;
printf(prefix);
if (!(line = malloc(nalloc_bytes)))
if (!fgets(buf, 128, stdin))
return NULL;
while ((c = getchar()) && c != '\n') {
if (nbytes + 1 >= nalloc_bytes) {
nalloc_bytes *= 2;
len = strlen(buf);
if (!(alloc = realloc(line, nalloc_bytes)))
goto err_free_line;
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = '\0';
line = alloc;
}
line[nbytes++] = c;
}
line[nbytes] = '\0';
return line;
putchar('\n');
err_free_line:
free(line);
return NULL;
return buf;
}
void cmd_exec(struct cmd *cmds, const char *line)
@ -88,6 +75,5 @@ void cmd_loop(const char *show)
while (!should_exit) {
line = prompt(show);
cmd_exec(main_cmds, line);
free(line);
}
}

Loading…
Cancel
Save