linux-sysprog · intermediate · ~15 min

Substitute $VAR with environment value

Combine string scanning with getenv and bounded output.

Challenge

Implement int env_subst(const char *in, char *out, size_t out_sz) that copies in to out while replacing each occurrence of $WORD (a $ followed by alphanumeric/underscore chars) with the value of the corresponding environment variable (or empty string if unset). Return 0 on success or -1 on overflow.

Starter code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int env_subst(const char *in, char *out, size_t out_sz) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.