typestar

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

  1. Never write through the pointer it hands back.
  2. A missing variable means falling back to a default.
  3. setenv and unsetenv are POSIX, not ISO C.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Program environment, step 3 of 14 in Systems programming.

← Previous Next →