如何在c ++中读取Linux环境变量 [英] How to read Linux environment variables in c++

查看:195
本文介绍了如何在c ++中读取Linux环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的c ++程序中,我想将一些环境变量从shell加载到一些字符串中。

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

推荐答案

使用getenv()函数 - 参见http://en.cppreference.com/w/cpp/utility/program/getenv 。我喜欢包装如下:

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;
     }
}

这避免了环境变量不存在时的问题,并允许我使用C ++字符串轻松地查询环境。当然,它不允许我测试环境变量是否不存在,但一般来说,这不是我的代码中的问题。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆