如何在c++中读取Linux环境变量

时间:2023-01-22 22:44:52

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

在我的c++程序中,我希望将一些环境变量从shell加载到一些字符串中。怎么做呢?

3 个解决方案

#1


35  

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/applicty/program/getenv。我想总结如下:

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

#2


8  

Same as in C: use getenv(variablename).

与C相同:使用getenv(变量名)。

#3


1  

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

here is a complete article about your problem, from my website.

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

#1


35  

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/applicty/program/getenv。我想总结如下:

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

#2


8  

Same as in C: use getenv(variablename).

与C相同:使用getenv(变量名)。

#3


1  

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

here is a complete article about your problem, from my website.

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