linux-sysprog · beginner · ~15 min
Read the environment with a fallback.
getenv returns NULL when a variable is unset. Wrap it so callers always get a usable value via a caller-supplied default.
Implement const char *getenv_or(const char *name, const char *dflt) that returns the value of environment variable name, or dflt if name is not set.
name: environment variable name to look up.dflt: fallback string returned when name is unset.The variable's value if set, otherwise dflt.
// CPLAT_TEST_VAR = "hi"
getenv_or("CPLAT_TEST_VAR", "x") -> "hi"
getenv_or("CPLAT_NOPE_VAR", "def") -> "def"
getenv returns NULL): return dflt.name: variable to look up; dflt: fallback when unset.
The variable's value, or dflt if unset.
Return dflt when getenv returns NULL.
#include <stdlib.h>
const char *getenv_or(const char *name, const char *dflt) {
/* TODO */
return dflt;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.