Accessing Environment Variables In C++(在 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 等效项 - System::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++ 中访问环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中访问环境变量
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
