Set and get environment variables in C

This is an example C program illustrating setting and getting an environment variable.

#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 it here.

The output of the example looks like this:

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

Ask and answer questions on C in the new C forum

Copyright © Ben Bullock 2009-2012. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (ben.bullock@lemoda.net) / Privacy / Disclaimer