如何在 C++ 中读取 Linux 环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5866134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read Linux environment variables in c++
提问by node ninja
In my c++ program I want to load some environment variables from the shell into some strings. How can this be done?
在我的 C++ 程序中,我想将一些环境变量从 shell 加载到一些字符串中。如何才能做到这一点?
回答by node ninja
Use the getenv() function - see http://en.cppreference.com/w/cpp/utility/program/getenv. I like to wrap this as follows:
使用 getenv() 函数 - 请参阅http://en.cppreference.com/w/cpp/utility/program/getenv。我喜欢这样包装:
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.
这避免了环境变量不存在时的问题,并允许我轻松地使用 C++ 字符串来查询环境。当然,它不允许我测试环境变量是否不存在,但总的来说,这在我的代码中不是问题。
回答by Axel
Same as in C: use getenv(variablename).
与 C 中相同:使用 getenv(variablename)。