linux-sysprog · intermediate · ~15 min
`getenv` and the convention "missing or empty means absent".
Look up an environment variable, falling back to a default when it is missing or empty.
Implement const char *getenv_default(const char *name, const char *fallback) returning the value of the environment variable name if it is set and non-empty, otherwise fallback. No main — the grader calls it.
name: the environment variable name to look up.fallback: the value to return when name is absent or set to the empty string.A pointer to the variable's value if set and non-empty, otherwise fallback.
CPLAT_TEST=hello -> getenv_default("CPLAT_TEST", "x") = "hello"
CPLAT_TEST="" -> getenv_default("CPLAT_TEST", "x") = "x"
CPLAT_TEST unset -> getenv_default("CPLAT_TEST", "y") = "y"
fallback).getenv; treat both NULL and the empty string as "not set".An environment variable name and a fallback string.
The variable's value if set and non-empty, otherwise fallback.
Treat NULL and the empty string both as "not set".
#include <stdlib.h>
const char *getenv_default(const char *name, const char *fallback) {
/* TODO */
return fallback;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.