Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Linux environment variables in c++

People also ask

What are the environment variables in C?

Standard environment variables are used for information about the user's home directory, terminal type, current locale, and so on; you can define additional variables for other purposes. The set of all environment variables that have values is collectively known as the environment.

How does Getenv work in C?

The getenv() function searches the environment variables at runtime for an entry with the specified name, and returns a pointer to the variable's value. If there is no environment variable with the specified name, getenv() returns a null pointer.

What does Getenv return in C?

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.


Use the getenv() function - see http://en.cppreference.com/w/cpp/utility/program/getenv. I like to wrap this as follows:

std::string GetEnv( const std::string & var ) {
     const char * val = std::getenv( var.c_str() );
     if ( val == nullptr ) { // invalid to assign nullptr to std::string
         return "";
     }
     else {
         return val;
     }
}

which avoids problems when the environment variable does not exist, and allows me to use C++ strings easily to query the environment. Of course, it does not allow me to test if an environment variable does not exist, but in general that is not a problem in my code.


Same as in C: use getenv(variablename).


You could simply use char* env[]

int main(int argc, char* argv[], char* env[]){
    int i;
    for(i=0;env[i]!=NULL;i++)
    printf("%s\n",env[i]);
    return 0;
}

here is a complete article about your problem, from my website.