The environment in C
getenv reads a variable, and returns NULL when it is not set.
#include <stdio.h>
#include <stdlib.h>
const char *setting(const char *name, const char *fallback) {
const char *value = getenv(name);
return (value != NULL && *value != '\0') ? value : fallback;
}
void show_config(void) {
printf("theme %s\n", setting("TYPESTAR_THEME", "default"));
printf("home %s\n", setting("HOME", "(unknown)"));
printf("shell %s\n", setting("SHELL", "/bin/sh"));
}
How it works
- Never write through the pointer it hands back.
- A missing variable means falling back to a default.
setenvandunsetenvare POSIX, not ISO C.
Keywords and builtins used here
NULLcharconstreturnsettingshow_configvoid
The run, in numbers
- Lines
- 13
- Characters to type
- 388
- Tokens
- 118
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 75 seconds.
Step 3 of 4 in Program environment, step 3 of 14 in Systems programming.