The getenv()
function returns a pointer to the string with the contents of the environment variable’s name, which is passed as the argument.
The function prototype for getenv()
is:
char * getenv(const char* env_var);
env_var
: a null-terminated string that identifies the name of the environment variable.
The getenv()
function returns a pointer to the c-string
containing the value of the environment variable that corresponds to env_var
. If no environment variable is found, it returns a null pointer
.
Environment variables are system-wide variables that are available to all processes in the system. These variables may contain information about the paths of certain executable files, the home directory, or the TEMP
directory (for storing temporary files).
#include <iostream>using namespace std;int main() {//list of possible environment variablesconst char* env_vars[3] = {"HOME", "PATH", "LOGNAME"};for (int i = 0; i < 3; i++){//Get the current path form the env variable $PATHconst char* content = getenv(env_vars[i]);//If variable exists print to stdoutif (content != NULL){cout << env_vars[i] << " = " << content << endl;}else{cout << env_vars[i] << " not found!" << endl;}}return 0;}
In the code above, we initialize a const char*
array of the possible environment variables available in the system. You can use the env
command in the terminal to see a full list of available environment variables.
Next, we loop through each element in the env_vars
array and pass it to the getenv()
function using the following code:
const char* content = getenv(env_vars[i]);
getenv()
will either return a pointer to the c-string
, that contains the value of the environment variable, or a null
pointer, if no such environment variable is found, and then store it in the content
variable.
The content
variable stores the value of the environment variable passed as an argument to getenv()
. For example, if we pass “PATH” as the argument, the function will return the current path of the system directory and store it in the content
variable.
Finally, we print the value pointed by content
if an environment variable with that name is found. If getenv()
returns a null-pointer
, we print out “not found!”
Free Resources