Here is a small example on how to set and get environmental variables using getnenv() and putenv() functions defined by C/C++ stdlib.h library. Environmental variable expansion is a great feature of a Linux shell as it enables programmers and users to rely on the environment settings of each user separately. C++ getenv() will read all exported environmental variables and putenv() will set existing or create new variables. Here is a small c++ program which can do this job:
#include <stdlib.h> #include <iostream> int main() { // get and print shell environmental variable home std::cout << "SHELL = " << getenv("SHELL") << std::endl; std::cout << "MYENV = " << getenv("MYENV") << std::endl; //set new shell environmental variable using putenv char mypath[]="TEMP=/my/new/temp/path/"; putenv( mypath ); std::cout << "TEMP = " << getenv("TEMP") << std::endl; return 0; }
Now lets' try to export new shell environment variable MYENV:
$ export MYENV=linuxconfig.org
Compile c++ program:
$ g++ shell_env.cpp -o shell_env
Run:
$ ./shell_env
Output:
SHELL = /bin/bash MYENV = linuxconfig.org TEMP = /my/new/temp/path/