Skip to content
systemcoding.dev
Systems Programming

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.

2 min read
Summarize in AI

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.

tokenize.cc
#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;
}
Text
[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.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.