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/

相关文章:

winapi - 如何取消提交文件映射页面?

windows - 如何找出在Windows中打开的EXE

c++ - c++ 结构是否有默认构造函数?

c++ - 自动生成位位置

c++ - 在字符串中输入换行符

html - 自动调整图像大小并缩小文件大小

c++ - 在扩展框架中绘制会产生奇怪的颜色

c++ - Unordered_map 使用 2D 点进行查找

c# - 多边形自动调整到其上面的多边形

c# - 从 C++(MSVC 编译器)调用 C# dll