shell: implement functions to parse command lines into an (argc, argv) tuple

tags/0.1.0
S.J.R. van Schaik 7 years ago
parent 7d0f730212
commit 5b97afd1bc
  1. 1
      Makefile
  2. 3
      include/shell.h
  3. 75
      source/shell/args.c

@ -37,6 +37,7 @@ obj-y += source/ftl/ftl.o
obj-y += source/ftl/gc.o
obj-y += source/ftl/map.o
obj-y += source/shell/args.o
obj-y += source/shell/cmd.o
obj-y += source/shell/flash.o
obj-y += source/shell/ftl.o

@ -1,5 +1,8 @@
#pragma once
size_t count_args(char *line);
char **parse_args(char *line, size_t *argc);
struct cmd {
const char *key;
void (* exec)(const char *line);

@ -0,0 +1,75 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <shell.h>
size_t count_args(char *line)
{
char *p = line;
size_t n = 0;
while (*p != '\0') {
p += strspn(p, " \n\r");
while (*p != '\0' && *p != ' ') {
if (*p++ != '\"')
continue;
while (*p != '\0' && *p != '\"')
++p;
if (*p == '\"')
++p;
}
++n;
}
return n;
}
char **parse_args(char *line, size_t *argc)
{
char **argv;
char **arg;
char *p = line;
char *s;
size_t n;
if (!argc)
argc = &n;
*argc = count_args(line);
if (!(argv = malloc(*argc * sizeof(char *) + strlen(line) + 1)))
return NULL;
arg = argv;
s = (char *)argv + *argc * sizeof(char *);
while (*p != '\0') {
p += strspn(p, " \n\r");
*arg++ = s;
while (*p != '\0' && *p != ' ') {
if (*p != '\"') {
*s++ = *p++;
continue;
}
++p;
while (*p != '\0' && *p != '\"')
*s++ = *p++;
if (*p == '\"')
++p;
}
*s++ = '\0';
}
return argv;
}
Loading…
Cancel
Save