Getenv(Obtain environment variable content)
Putenv, setenv, unsetenv
Header file # include <stdlib. h>
Define the function char * getenv (const char * Name );
Function Description getenv () is used to obtain the content of the parameter name environment variable. The parameter name is the name of the environment variable. If the variable exists, a pointer to the content is returned. The environment variable format is name = value.
Return Value: if the execution is successful, the pointer pointing to the content is returned. If no conforming environment variable name is found, null is returned.
Example
?
# Include <stdlib. h> Mian () {
Char * P;
If (P = getenv ("user "))) Printf ("user = % s \ n", P ); } |
Displayed after execution:
User = root
Putenv(Change or add environment variables)
Related functions: getenv, setenv, and unsetenv
Header file # include <stdlib. h>
Defines the int putenv (const char * string) function );
Function Description: putenv () is used to change or add environment variables. The format of the parameter string is name = value. If the environment variable originally exists, the content of the variable changes according to the string parameter. Otherwise, the content of this parameter becomes a new environment variable.
Return Value: if the execution is successful, 0 is returned. If an error occurs,-1 is returned.
ErrorCode: The enomem memory is insufficient and the new environment variable space cannot be configured.
Example
?
# Include <stdlib. h> Main () {
Char * P;
If (P = getenv ("user "))) Printf ("user = % s \ n", P ); Putenv ("user = test "); Printf ("user = % s \ n", getenv ("user ")); } |
Run user = root
User = test
Setenv(Change or add environment variables)
Related functions: getenv, putenv, and unsetenv
Header file # include <stdlib. h>
Defines the function int setenv (const char * Name, const char * value, int overwrite );
Function Description: setenv () is used to change or add environment variables.
The parameter name is an environment variable name string.
The parameter value is the variable content.
The overwrite parameter is used to determine whether to change an existing environment variable. If the value of overwrite is not 0, the original content of the environment variable will be changed to the variable content referred to by the parameter value. If overwrite is 0 and the environment variable already contains content, the parameter value is ignored.
If the return value is successfully executed, 0 is returned. If an error occurs,-1 is returned.
Error code: insufficient enomem memory, unable to configure new environment variable space
Example
# Include < Stdlib. h >
Main ()
{
Char * P;
If (P = Getenv ("user ")))
Printf ("User = % S \ n ", P );
Setenv ("user", "test ", 1 );
Printf ("User = % S \ n ", getenv (" user "));
Unsetenv ("user ");
Printf ("User = % S \ n ", getenv (" user "));
}
Run
User = root
User = test
User = (null)