Set and get environment variables in C

This example C program illustrates how to set and get an environment variable from C.

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

static void
run_getenv (const char * name)
{
    char * value;

    value = getenv (name);
    if (! value) {
        printf ("'%s' is not set.\n", name);
    }
    else {
        printf ("%s = %s\n", name, value);
    }
}

int main ()
{
    char * name = "moo";
    /* Variable is not set. */
    run_getenv (name);
    /* Write into empty variable. */
    setenv ("moo", "chops", 0);
    run_getenv (name);
    /* This doesn't change the value because "overwrite" is 0. */
    setenv ("moo", "drops", 0);
    run_getenv (name);
    /* This changes the value because "overwrite" is 1. */
    setenv ("moo", "drops", 1);
    run_getenv (name);

    return 0;
}

(download)

The output of the example looks like this:

'moo' is not set.
moo = chops
moo = chops
moo = drops


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer