Reputation: 32986
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
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
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