add, change or delete an environment variable
#include <process.h> int putenv( const char *env_name );
The environment list consists of a number of environment names, each of which has a value associated with it.
Format of env_name | Action |
---|---|
env_name=value | An environment name and its value are added to the environment list. |
env_name= | The environment name and value are removed from the environment list. |
The matching is case-sensitive; all lowercase letters are treated as different from uppercase letters. |
The space into which environment names and their values are placed is limited. Consequently, the putenv() function can fail when there is insufficient space remaining to store an additional value.
The putenv() function affects only the environment that's local to the current process; you can't use it to modify the command-level environment. That is, this function operates only on data structures accessible to the runtime library and not on the environment "segment" created for a process by the operating system. When the current process terminates, the environment reverts to the level of the calling process (in most cases, the operating-system level). However, the modified environment can be passed to any new processes created by the spawn... functions, exec... functions, or system(), and these new processes get any new items added by putenv().
With regard to environment entries, observe the following cautions:
|
To use the export command to assign a string to a variable and place it in the environment list, type something like the following:
export INCLUDE=/usr/include
Type the export command without any arguments to see what variables are in the environment list, and their current assignments. An example of the output is as follows:
SHELL=ksh TERM=qnx LOGNAME=fred PATH=:/bin:/usr/bin HOME=/home/fred INCLUDE=/usr/include LIB=/usr/lib
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 the environment name and value.
#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=//5/usr/include" ) != 0 ) printf( "putenv failed" ); path = getenv( "INCLUDE" ); if( path != NULL ) printf( "INCLUDE=%s\n", path ); if( putenv( "INCLUDE=" ) != 0 ) printf( "putenv failed" ); return (EXIT_SUCCESS); }
This program produces the following output:
INCLUDE=/usr/include INCLUDE=//5/usr/include
UNIX
Safety: | |
---|---|
Interrupt handler | No |
Signal handler | No |
Thread | Yes |
clearenv(), errno, getenv(), setenv()