C++

How to Access the Environment in C++

C++ is the most efficient high-level language for programming. C++ facilitates us with a variety of function libraries and allows us to handle the exceptions and the overloading of a function. We can also get the environment in C++ with the help of the getenv() function. These environment variables are found in the OS that all programming languages operate on and can be accessed in some way. The getenv() function gives the C++ programming language access to these capabilities. Using the C++ getenv() method, the pointer to the C string that contains the contents of the supplied environment variables is returned as a parameter. Here, we will learn this concept and check how we will access the environment in our C++ programming with the help of examples.

Example 1:

We simply begin with our first example here. To do the C++ codes, we need some header files. So, we include the header files that we require in this code. The “iostream” header file is essential because, in this code, we need to display some data and this header file supports the “cout” function. Then, we have “cstdlib”; this header provides a set of methods like the “getenv()” method.

Now, we add the “namespace std” so we don’t need to add “std” with the “cout()” functions in our code. After this, the “main()” function is called. Then, we place “char*” which is a pointer here with the name “var_1”. Then, in this “var_1” variable, we place the “getenv()” function and pass the “SESSIONNAME” as its parameter.

After this, we add an “if” condition which checks whether the “var_1” is not equal to “NULL”. If “var_1” is not null, it prints the environment variable name first. Then, in the next line, it prints the value of that variable. But if “var_1” is “NULL”, it will not display any message there and the code terminates.

Code 1:

 #include <iostream>      
#include <cstdlib>    
using namespace std;
int main ()
{
  char* var_1;
  var_1 = getenv ("SESSIONNAME");
  if (var_1!=NULL)
    cout << "The variable name is SESSIONNAME" << endl;
    cout << "The environment variable is: " << var_1;
  return 0;
}

Output:
This output renders the name of the environment variable which we add as the parameter of the “getenv()” function and the value of this environment variable. We get this value with the help of the “getenv()” function in our code.

Example 2:

Now, we have another example. We start our code by including the necessary header files. Then, we type “namespace std”. After this, we access the “main()” function in which we create a “char* ” pointer named “newEnv_var” and initialize it with the “Path” environment variable name. Then, we add another “char* ” which is also a pointer here and name it “myValue”.

Now, we initialize the “myValue” variable with the “getenv()” function and pass the “newEnv_var” to this “getenv()” function; it is the parameter of this function. This “newEnv_var” variable contains the name of the environment variable as we initialize it with “PATH”. Next, an “if” condition is added to determine whether “myValue” is equivalent to “NULL” or not. If “myValue” is not null, the environment variable name is printed first, followed by the variable’s value in the next line. However, if “myValue” is set to “NULL”, no message is displayed and the code ends here.

Code 2:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    char* newEnv_var = "PATH";
    char* myValue;
    myValue = getenv(newEnv_var);
    if (myValue != NULL) {
        cout << "The variable = " << newEnv_var << endl;
        cout << "The value = " << myValue << endl;
    }
    else
        cout << "Variable doesn't exist!" << myValue;
    return 0;
}

Output:
Now, on the terminal, it shows the value of the “PATH” environment variable which we get using the “getenv()” function in our code. It differs on every computer since the path on each computer is different.

Example 3:

Here’s another example: we type “namespace std” at the beginning of our code after incorporating the required “iostream” and “cstdlib” header files. Next, we enter the “main()” method where we generate a “char*” pointer called “myVar” and initialize the “PUBLIC” environment variable name.

Next, we create a new “char*” called “myValue”; this one is also a pointer. Now that “myVar” is supplied to the “getenv()” function, with which we initialize the “myValue” variable, it is a function argument. Since we initialize it with “PUBLIC”, the environment variable name is contained in this “myVar” variable.

Then, to ascertain whether “myValue” is equal to “NULL” or not, an “if” condition is added. The environment variable name will appear first on the screen if “myValue” is not null, and the variable’s value will appear on the next line. Then, we have the other part added here which executes if the given condition is not satisfied. Here, we print a message which tells us that the “Variable not found here”.

Code 3:

#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
    char* myVar = "PUBLIC";
    char* myValue;
    myValue = getenv(myVar);
    if (myValue != NULL) {
        cout << "The Variable = " << myVar << endl;
        cout << "It's Value= " << myValue << endl;
    }
    else
        cout << "Variable not found here..!!" << myValue;
    return 0;
}

Output:
The name of the environment variable that we add as a parameter to the “getenv()” function, together with its value, is rendered in this output. We can obtain this value using our code’s “getenv()” function.

Example 4:

We create a constant char array named “NewEnv_var[]” here with the size of “6”. Then, we pass all possible environment variables to this array. Below this, we have another array named “char *env_value[]” with the same size of “6”. Now, we have a “for” loop and we loop all these environment variables from the “getenv()” function to get the values of all these variables and store them in the “env_value” array. Inside this “for” loop, we also place an “if” condition that checks whether the environment value is null. If the value is not null, it prints the value and the variable name. If it is null, it shows a message that the environment variable doesn’t exist here.

Code 4:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    const char *NewEnv_var[6] = {"PUBLIC","HOME","SESSIONNAME","LIB","SystemDrive", "DELTREE"};
    char *env_value[6];
    for(int a=1; a<=6; a++)
    {      
        env_value[a] = getenv(NewEnv_var[a]);
        if (env_value[a] != NULL)
            cout << "The variable is " << NewEnv_var[a] << ", and it's 'Value= " << env_value[a] << endl;
        else
            cout << NewEnv_var[a] << " doesn't exist here " << endl;
    }
}

Output:
Here, it shows all the possible values of the environment variable and also shows the message that “HOME”, “LIB”, and “DELTREE” don’t exist which means that their value is NULL.

Example 5:

Now, let’s ahead. This is the last example of this tutorial. Here, we establish a constant char array of size “4” called “Variable[]” to which we provide all potential environment variables. We now use a “for” loop. Below this, there’s another array with the same size of “4” called “char *values[]” and we place the “getenv()” function there and passe the “variable[i]” as its parameter. This loop is utilized to iterate over all of the environment variables, retrieving their values from the “getenv()” function and saving them in the “values[]” array.

We include the “if” condition within this “for” loop that determines whether the environment value is null or not. The value and the variable name are printed if the value is not null, and a message is displayed if it is NULL which is provided in the “else” part.

Code 5:

#include <iostream>
using namespace std;
int main() {
  const char* variable[4] = {"PUBLIC", "HOME", "DELTREE", "LOGNAME"};
  for (int i = 0; i <= 4; i++)
  {
    const char* values = getenv(variable[i]);
    if (values != NULL){
      cout << variable[i] << " = " << values << endl;
    }
    else{
      cout << variable[i] << " not found here!" << endl;
    }
  }
  return 0;
}

Output:
In this case, the environment variable’s possible values are displayed along with the notification that the values of “HOME”, “DELTREE”, and “LONGNAME” are not found here which means that they are NULL values.

Conclusion

This tutorial is all about “how to access the environment in C++”. We explored the examples in which we learned how to access the environment variable individually or using the array in which we pass all the possible environment variables and then get the values by utilizing the “getenv()” function. This “getenv()” method is provided by the C++ language to get the required environment variable values.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.