在C ++中访问环境变量 [英] Accessing Environment Variables In C++
问题描述
我想要访问我正在写的C ++程序中的$ HOME环境变量。如果我在C编写代码,我只是使用getenv()函数,但我想知道是否有一个更好的方法来做到这一点。这里是我到目前为止的代码:
I'd like to have access to the $HOME environment variable in a C++ program that I'm writing. If I were writing code in C, I'd just use the getenv() function, but I was wondering if there was a better way to do it. Here's the code that I have so far:
std::string get_env_var( std::string const & key ) {
char * val;
val = getenv( key.c_str() );
std::string retval = "";
if (val != NULL) {
retval = val;
}
return retval;
}
我应该使用getenv()来访问C ++中的环境变量吗?是否有任何问题,我可能会遇到,我可以避免与一点知识?
Should I use getenv() to access environment variables in C++? Are there any problems that I'm likely to run into that I can avoid with a little bit of knowledge?
推荐答案
在C ++中使用 getenv()
没有什么问题。它由 stdlib.h
定义,或者如果您喜欢标准库实现,可以包括 cstdlib
并访问函数通过 std ::
命名空间(即 std :: getenv()
)。这绝对没有错。
There is nothing wrong with using getenv()
in C++. It is defined by stdlib.h
, or if you prefer the standard library implementation, you can include cstdlib
and access the function via the std::
namespace (i.e., std::getenv()
). Absolutely nothing wrong with this. In fact, if you are concerned about portability, either of these two versions is preferred.
如果你不是关注可移植性,而且你是可移植性的,使用托管C ++,您可以使用.NET等效项 - 系统: :Environment :: GetEnvironmentVariable()
。如果您希望在Windows中使用非.NET等效项,则只需使用 GetEnvironmentVariable()
Win32函数。
If you are not concerned about portability and you are using managed C++, you can use the .NET equivalent - System::Environment::GetEnvironmentVariable()
. If you want the non-.NET equivalent for Windows, you can simply use the GetEnvironmentVariable()
Win32 function.
这篇关于在C ++中访问环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!