Composition of environmental variables
Environment variables consist of a pair of strings in the form of: variable = associated value. For example:
PATH=C:\WINDOWS
In DOS and Windows, you can define an environment variable from the command line or in a batch file by using the SET command followed by an assignment expression. Here is an example of creating an environment variable,
SET VERSION=1.1.3
The preceding set can be omitted from UNIX, written as:
VERSION=1.1.3
Reading environment variables
The program can only access the environment variables at startup, and the environment variable consists of a string array in the form of "Var=value". You can access environment variables from your program with the getenv () and putenv () functions.
The ANSI C function getenv () provides a simple and easy way to access an environment variable, which is declared in <stdlib.h>, and the prototype is as follows:
char * getenv(const char * name);
If the function call succeeds, it returns the string value of the environment variable. If the variable is not defined, the function returns Null (NULL). For example:
#include <stdlib.h>
#include <stdio.h>
int main()
{
char * descr = getenv("PATH");
if (descr)
printf("value of PATH is: %s", descr);
else
printf("variable not defined");
}
Setting environment variables
To define an environment variable or to change the existing variable value, use the Putenv () function. This function is not defined by the standard Ansi/iso. In practical applications, UNIX and Windows have defined this function as a non-standard extension in <stdlib.h> files, which is portable. The prototype is as follows:
int putenv(const char * var);
Parameter VAR must be a string, and the format must be "Var=val". Putenv () adds the variable var to the current environment variable and assigns the Val. If the variable already exists, putenv () overwrites the existing value. If you do not want to overwrite the value of an existing variable, call getenv () first to check if the variable exists, and then call Putenv (). The following example adds an environment variable named TEMP to C:\TEMP (note how the backslash is represented in a C + + string). If the call succeeds, putenv () returns 0, otherwise, returns-1.
int stat = putenv("TEMP=C:\\TEMP");
if (!stat)
{
printf("环境变量定义失败");
}