c++ - GetEnvironmentVariableA() 用法

标签 c++ visual-studio winapi visual-c++ environment-variables

我正在 Windows 7 上的 Visual Studio 2012 中开发 C++ 控制台应用程序,我想从应用程序中获取一些环境变量的值。
这是我到目前为止尝试过的 - :

int main()
{
    char a[1000];
    int s=GetEnvironmentVariableA("HOME",a,1000);
}  

但是,我得到的 s 的值为 0,表示变量“HOME”不存在。
此外,getenv("HOME") 也返回 NULL
那么,这样做的正确程序是什么?

最佳答案

这个程序最有可能告诉您的是,您的进程环境不包含名为 HOME 的变量。请注意,HOME 不是您希望定义的变量,除非您已采取步骤来定义它。通过将其添加到系统环境,或在创建流程时指定定制环境。

documentation关于返回值的说明如下:

If the function succeeds, the return value is the number of characters stored in the buffer pointed to by lpBuffer, not including the terminating null character.

If lpBuffer is not large enough to hold the data, the return value is the buffer size, in characters, required to hold the string and its terminating null character and the contents of lpBuffer are undefined.

If the function fails, the return value is zero. If the specified environment variable was not found in the environment block, GetLastError returns ERROR_ENVVAR_NOT_FOUND.

因此,如果函数返回 0,请按照文档中的说明进行操作。调用 GetLastError 找出函数调用失败的原因。

但正如我所说,概率非常接近 1,原因很简单,就是您的进程环境没有定义名为 HOME 的变量。

至于您如何前进,您很可能正在寻找用户个人资料中的位置。具体如何执行此操作将取决于您希望在配置文件中存储/加载文件的位置。与 CSIDL 或已知文件夹 ID 相关的 API 之一将满足您的需求。

关于c++ - GetEnvironmentVariableA() 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24124851/

相关文章:

c++ - 在 C++ 中创建一个大数组

c++ - 用异构 boost::fusion vector 类型数据填充 std::vector

winapi - 谁在 SetClipboardData(CF_BITMAP, HBITMAP) 中释放句柄?

winapi - Win32 CRITICAL_SECTION 包含什么?

c++ - 我如何创建两个不同的类,在它们的代码中相互引用?

c++ - 如果我从 getter 生成迭代器,程序将中止

asp.net - NuGet - 给定类型名称或 DLL,如何找到 NuGet 包?

c# - 从同一项目访问 XSLT 文件作为资源?

c++ - 无法在 Visual Studio Community 2015 中编译基本程序(LNK2019 - MSVCRTD.lib)

winapi - Discord如何挂接到特定进程的音频中?