且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取当前用户的主目录在Windows

更新时间:2023-01-13 12:52:44

使用函数 SHGetFolderPath 。此函数优先于查询环境变量,因为后者可以修改为指向错误的位置。文档包含一个示例,我在此重复(稍作调整):

Use the function SHGetFolderPath. This function is preferred over querying environment variables since the latter can be modified to point to a wrong location. The documentation contains an example, which I repeat here (slightly adjusted):

#include <Shlobj.h>  // need to include definitions of constants

// .....

WCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path))) {
  ...
}