如何在c ++中读取Linux环境变量 [英] How to read Linux environment variables in c++
本文介绍了如何在c ++中读取Linux环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
使用getenv()函数 - 参见 http://en.cppreference.com/w/cpp/utility/program/getenv 。我喜欢如下所示:
string GetEnv(const string& var){
const char * val = :: getenv(var.c_str());
if(val == 0){
return;
}
else {
return val;
}
}
当环境变量不存在时,避免了问题,并允许我轻松使用C ++字符串查询环境。当然,它不允许我测试一个环境变量是否不存在,但一般来说这不是我的代码中的问题。
In my c++ program I want to load some environment variables from the shell into some strings. How can this be done?
解决方案
Use the getenv() function - see http://en.cppreference.com/w/cpp/utility/program/getenv. I like to wrap this as follows:
string GetEnv( const string & var ) {
const char * val = ::getenv( var.c_str() );
if ( val == 0 ) {
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 ++中读取Linux环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文