简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM