在我的 c++ 程序中,我想将一些环境变量从 shell 加载到一些字符串中。如何做到这一点?
最佳答案
使用 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;
}
}
这避免了环境变量不存在时的问题,并允许我轻松使用C++字符串来查询环境。当然,它不允许我测试环境变量是否不存在,但总的来说这在我的代码中不是问题。
关于c++ - 如何在 C++ 中读取 Linux 环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866134/