Hello, Environment

The operating system keeps several variables in memory, variables that hold information necessary to running the computer. For example, the path variable lists directories in which the operating system looks for programs. The prompt variable describes how to display the command prompt. Some programs even create variables, allowing the programs to save configuration or other information.

To read the environment, your program uses the environ pointer array. It must be declared as an external variable, as shown in the following code:

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

extern char **environ;

int main()
{
    while(*environ)
    {
        printf("%s\n",*environ);
        environ++;
    }
    return(0);
}

The code above dumps the environment by plowing through the environ array one string at a time. (The environ variable is declared in the stdlib.h header file.)

When you know a specific value to fetch, you use the getenv() function, as demonstrated in the following code:

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

int main()
{
    char *searchpath;

    searchpath = getenv("PATH");
    printf("The search path is '%s'\n",searchpath);
    return(0);
}

The code above uses the getenv() function to fetch the PATH environment variable. A pointer to that variable is returned, which the program stores in the local address searchpath. Further manipulation of the path would require additional code, for example, to check to see whether a specific directory is on the path or not.

While you could manipulate the environment by checking the environ variable, the man pages recommend that you use getenv() to fetch items. More importantly, you should use the putenv() function to add an item to the environment or the setenv() or unsetenv() functions to change an item.

Leave a Reply