putenv()

Add, change or delete an environment variable

Synopsis:

#include <stdlib.h>

int putenv( char *env_name );

Arguments:

env_name
The name of the environment, and what you want to do to it; see below.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The putenv() function uses env_name, in the form name=value, to set the environment variable name to value. This function alters name if it exists, or creates a new environment variable.

In either case, env_name becomes part of the environment; subsequent modifications to the string pointed to by env_name affect the environment.

The space for environment names and their values is limited. Consequently, putenv() can fail when there's insufficient space remaining to store an additional value.

Note: If env_name isn't a literal string, you should duplicate the string, since putenv() doesn't copy the value. For example:
putenv( strdup( buffer ) );

Returns:

0
Success.
-1
An error occurred; errno is set.

Errors:

ENOMEM
There wasn't enough memory to expand the environment.

Examples:

The following gets the string currently assigned to INCLUDE and displays it, assigns a new value to it, gets and displays it, and then removes INCLUDE from the environment.

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

int main( void )
{
    char *path;
    path = getenv( "INCLUDE" );
    if( path != NULL ) {
        printf( "INCLUDE=%s\n", path );
    }

    if( putenv( "INCLUDE=/src/include" ) != 0 ) {
        printf( "putenv() failed setting INCLUDE\n" );
        return EXIT_FAILURE;
    }

    path = getenv( "INCLUDE" );
    if( path != NULL ) {
        printf( "INCLUDE=%s\n", path );
    }

    unsetenv( "INCLUDE" );
    
    return EXIT_SUCCESS;
}

This program produces the following output:

INCLUDE=/usr/nto/include
INCLUDE=/src/include

Classification:

POSIX 1003.1 XSI

Safety:  
Cancellation point No
Interrupt handler No
Signal handler No
Thread No

Caveats:

Never use putenv() with an automatic variable.

The putenv() function manipulates the environment pointed to by the global environ variable.