Split a command line into argv with an in-place tokenizer
Split a command line into argv in place by writing NUL bytes over spaces and handling double quotes, with no allocation, for a small shell in C.
The first job of a shell is turning ls -l "my file" into an array of words. This is an example of a tokenizer that works in place: it walks the line once, writes a NUL where each word ends, and stores pointers into the same buffer, so there is nothing to free. It understands double quotes, and nothing else, which keeps it short.
#include <stdio.h>
int tokenize(char *line, char **argv, int max) {
int argc = 0;
char *p = line;
while (*p && argc < max - 1) {
while (*p == ' ' || *p == '\t' || *p == '\n') p++;
if (!*p) break;
char *dst = p;
argv[argc++] = dst;
int quoted = 0;
while (*p && (quoted || (*p != ' ' && *p != '\t' && *p != '\n'))) {
if (*p == '"') { quoted = !quoted; p++; continue; }
*dst++ = *p++;
}
if (*p) p++;
*dst = '\0';
}
argv[argc] = NULL;
return argc;
}
int main(void) {
char line[] = "ls -l \"my file\" b\n";
char *argv[16];
int n = tokenize(line, argv, 16);
for (int i = 0; i < n; i++) printf("[%s]\n", argv[i]);
return 0;
}[ls]
[-l]
[my file]
[b]The destination pointer trails the source pointer, so removing the quote characters shifts the text left without a second buffer. The NULL at the end is what execvp needs. The input must be writable, which a string literal is not. There is no escape for a quote inside quotes, no single quotes and no variable expansion, so this is a starting point. Check the line length first, and report an unterminated quote instead of accepting it silently.