如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:54:04  来源:igfitidea点击:

How to read Linux environment variables in c++

c++linuxenvironment-variables

提问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)。

回答by hanoo

You could simply use char* env[]

你可以简单地使用 char* env[]

int main(int argc, char* argv[], char* env[]){
    int i;
    for(i=0;env[i]!=NULL;i++)
    printf("%s\n",env[i]);
    return 0;
}

hereis a complete article about your problem, from my website.

是一篇关于您的问题的完整文章,来自我的网站