36

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

3 Answers 3

45

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.

5
  • 1
    Sometimes you may want to differentiate between 'unset' and 'empty'
    – sehe
    May 3, 2011 at 7:03
  • 1
    Must.... make...... template..... predicated on.... CharT. Oh wait, that requires SFINAE. Oh well. +1 May 3, 2011 at 7:08
  • 1
    you might use boost::optional<std::string> as a return type to differentiate between absent and empty. May 3, 2011 at 7:09
  • 5
    @Matthieu I would say 99% of the time I don't care if an env variable actually exists - I just want to know its value and am happy with an empty string if it doesn't. Rather than complicate things enormously by bringing boost into the picture, I would simply test for existence by calling getenv() directly. Or possibly write a EnvVarExists() function.
    – user2100815
    May 3, 2011 at 7:14
  • 2
    I was more thinking about the case where you might want a sensible default, but this can be achieved by providing an overload with a second parameter :) May 3, 2011 at 7:21
9

Same as in C: use getenv(variablename).

4

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.

4
  • 1
    Thanks for posting your answer! Please be sure to read the FAQ on Self-Promotion carefully. Also note that it is required that you post a disclaimer every time you link to your own site/product. Oct 30, 2012 at 8:51
  • 2
    It's "function", not "fonction". (Referring to your website.) Also, the third parameter to main() is non-standard, and not guaranteed to work on all platforms / compilers.
    – DevSolar
    Oct 30, 2012 at 9:00
  • does this work with environment variables that are exported/set after the program starts ?
    – nurettin
    Nov 14, 2013 at 11:29
  • nurettin: I think so but try to be sure ;)
    – hanoo
    Nov 14, 2013 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.