Syntax
#include <stdlib.h> int putenv(char *envstring);Description
putenv adds new environment variables or modifies the values of existing environment variables. Environment variables define the environment in which a process runs (for example, the default search path for libraries to be linked with a program).
The envstring argument must be a pointer to a string with the form:
varname=stringwhere varname is the name of the environment variable to be added or modified and string is the value of the variable. See the Notes below.
If varname is already part of the environment, string replaces its current value; if not, the new varname is added to the environment with the value string. To set a variable to an empty value, specify an empty string. A variable can be removed from the environment by specifying varname only, for example:
putenv("PATH");
Do not free the envstring pointer while the entry it points to is in use, or the environment variable will point into freed space. A similar problem can occur if you pass a pointer to a local variable to putenv and then exit from the function in which the variable is declared. Once you have added the envstring with putenv, any change to the entry it points to changes the environment used by your program.
The environment manipulated by putenv is local to the process currently running. You cannot enter new items in your command-level environment using putenv. When the program ends, the environment reverts to the parent process environment. This environment is passed on to some child processes created by the _spawn, exec, or system functions, and they get any new environment variables added using putenv.
DosScanEnv will not reflect any changes made using putenv, but getenv will reflect the changes.
Note:
Returns
putenv returns 0 if it is successful. A return value of -1 indicates an error.
This example tries to change the environment variable PATH, and then uses getenv to get the current path. If the call to putenv fails, the example writes an error message.
#include <stdlib.h>#include <stdio.h> int main(void) { char *pathvar; if (-1 == putenv("PATH=a:\\bin;b:\\andy")) { printf("putenv failed - out of memory\n"); return EXIT_FAILURE; } /* getting and printing the current environment path */ pathvar = getenv("PATH"); printf("The current path is: %s\n", pathvar); return 0; /**************************************************************************** The output should be: The current path is: a:\bin;b:\andy ****************************************************************************/ }Related Information