Accessing Environment Variables In C++
There is nothing wrong with using getenv()
in C++. It is defined by stdlib.h
, or if you prefer the standard library implementation, you can include cstdlib
and access the function via the std::
namespace (i.e., std::getenv()
). Absolutely nothing wrong with this. In fact, if you are concerned about portability, either of these two versions is preferred.
If you are not concerned about portability and you are using managed C++, you can use the .NET equivalent - System::Environment::GetEnvironmentVariable()
. If you want the non-.NET equivalent for Windows, you can simply use the GetEnvironmentVariable()
Win32 function.
I would just refactor the code a little bit:
std::string getEnvVar( std::string const & key ) const
{
char * val = getenv( key.c_str() );
return val == NULL ? std::string("") : std::string(val);
}