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

查看:37
本文介绍了如何在 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:

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++字符串来查询环境.当然,它不允许我测试环境变量是否不存在,但总的来说这在我的代码中不是问题.

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天全站免登陆