getenv

The getenv function is used to lookup the value of variables in the system's environment. The function will receive as parameter the name of the environment variable that we are interested in finding, and will return the value found, if any.

The getenv function requires one argument, a pointer to a NULL terminated string which identifies the variable that we are searching in the system's environment. Its return value is also a pointer to a NULL terminated string, representing the result of the search. If the search was successful, getenv will return the content of the environment variable. Otherwise, the pointer returned will be NULL.

The getenv function normally searches the environment variables in the global variable "environ", which is made available by the C runtime. The strings returned are owned by the system, and should not be freed by the application.

The following code shows an example of getenv in use:

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

int main()
{
        char *path;
        char *var = "PATH";
        path = getenv(var);
        if (path)
                printf("the variable %s has value %s\n", var, path);
        return 0;
}

This will print the current PATH environment variable in the local computer.

Article created on 2008-08-19 21:58:02

Post a comment