Environment Variable Functions in Linux
1. You can use the env and set commands on the terminal to view the current environment variables.
2. Use the third parameter in the main function to obtain the list of environment variables of the current process.
Int main (int argc, char * argv [], char * env []);
Where argv and env are a pointer array, and the last element of the array is NULL.
3. Print the environment variables of the current process
int main(int argc , char *argv[] , char *env[]){ char **p = env; while(*p){ printf("%s\n",*env); env++; }}
4. getenv obtains the specified environment variable.
Char * getenv ("environment variable name ")
int main(){ char * p = getenv("PATH"); if(p){ printf("%s",p); } else{ return; } }
5. Set the environment variable in putenv.
int main(int argc , char ** argv , char **env){ printf("%s\n",getenv("PATH")); putenv("PATH=/home/hello"); printf("%s\n",getenv("PATH"));}
Output result:
/Usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/Home/hello
6. setenv: Set Environment Variables
First, it must be noted that this function does not allow you to add or modify the environment variables of the shell process, or the environment variables set through the setenv function are only valid for this process. If the setenv function is executed when a program is run and the program is run again after the process is terminated, the last setting is invalid and the environment variables set last time cannot be read.
Setenv ("variable name", "new variable value", "Overwrite ")
Int main (int argc, char ** argv, char ** env) {printf ("% s \ n", getenv ("PATH ")); int res = setenv ("PATH", "/home/hello", 1); // The third parameter 1 indicates rewriting if (res =-1) return; printf ("% s \ n", getenv ("PATH "));}
Output result:
/Usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/Home/hello
If the third parameter is 0, that is, the environment variable already exists, its value is not changed.
Output result:
/Usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/Usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
7. unsetenv: delete an environment variable
Unsetenv ("environment variable name ")
int main(int argc , char ** argv , char **env){ printf("%s\n",getenv("PATH")); unsetenv("PATH"); printf("%s\n",getenv("PATH"));}
Output result:
/Usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
The PATH is deleted, so only one row is output.