C++ getenv() Function
The getenv() function in C++ is used to return a pointer to the C string that contains the value of the environment variable passed as an argument.
Environment variables are dynamic-named values that can affect the way running processes will behave on a computer. Each operating system offers environment variables, as that allows the newly installed programs to identify important directories (ex. Home, Profile, Bin, etc.) with ease. All programming languages offer some way of accessing such environment variables that are present in the operating system on which they are running. This functionality is provided to the C++ language via the function getenv. In this article, you will learn about the getenv function in C++.
This function is defined in <cstdlib> header file.
char *getenv(const char *name)
Parameters: Here, the name is String (or char array) containing the name of the requested environment variable,
Return value: A string containing the value of the requested environment variable or NULL Pointer if the variable is not found.
Variable = PATH Value= /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Explanation: A variable named env_variable is assigned the name of the environment variable whose value is requested. Another variable value is declared which will store the return value from the getenv function. Then the name of the environment variable is passed to the getenv function. The function searches for the name of the environment variable in the list of environment variables it has. If the variable is found, then its value of the environment variable is returned. Otherwise, a NULL value is returned. After which in an if condition the value stored in the variable value is checked. If the value is NULL (meaning a variable with such a name doesn’t’ exists) then display such a message. Otherwise, display the value associated with that variable.
Variable doesn't exist!
Explanation: Since the variable doesn’t exist the program displays Variable doesn’t exist! This message would also be displayed if a variable is added while the program is running. As the program copies the list of environment variables from the OS before the execution of the program.
Please Login to comment...