Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use getenv() in C++

Muhammad Ashir

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);

Parameters

env_var: a null-terminated string that identifies the name of the environment variable.

Return Value

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).

Code

#include <iostream>
using namespace std;

int main() {
  
  //list of possible environment variables
  const char* env_vars[3] = {"HOME", "PATH", "LOGNAME"};
  
  for (int i = 0; i < 3; i++)
  {
    //Get the current path form the env variable $PATH
    const char* content = getenv(env_vars[i]); 

    //If variable exists print to stdout
    if (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!”

RELATED TAGS

c++

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring