node ninja
node ninja

Reputation: 32986

How to read Linux environment variables in c++

In my c++ program I want to load some environment variables from the shell into some strings. How can this be done?

Upvotes: 37

Views: 37259

Answers (3)

hanoo
hanoo

Reputation: 4245

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.

Upvotes: 4

user2100815
user2100815

Reputation:

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.

Upvotes: 45

Axel
Axel

Reputation: 14159

Same as in C: use getenv(variablename).

Upvotes: 9

Related Questions