Add, change or delete an environment variable
#include <stdlib.h> int putenv( char *env_name );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
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.
putenv( strdup( buffer ) );
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
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
Never use putenv() with an automatic variable.
The putenv() function manipulates the environment pointed to by the global environ variable.