如何获取当前用户的主目录路径?
例如: 在Windows中,如果当前用户是“guest”,我需要“C:\Users\guest”
我的应用程序将在大多数Windows版本(XP,Vista,Win 7)上运行。
如何获取当前用户的主目录路径?
例如: 在Windows中,如果当前用户是“guest”,我需要“C:\Users\guest”
我的应用程序将在大多数Windows版本(XP,Vista,Win 7)上运行。
使用函数SHGetFolderPath
。与查询环境变量相比,此函数更受欢迎,因为后者可能会被修改以指向错误的位置。文档中包含一个示例,在此稍作调整并重复:
#include <Shlobj.h> // need to include definitions of constants
// .....
WCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path))) {
...
}
%HOMEPATH%
结合 %SystemDrive%
以实现。具体信息请参考 http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows。SystemDrive
环境变量。请使用SHGetFolderPathW
,它始终正确,在所有支持的Windows版本上都可以工作,并且更易于使用。 - Philipp%HOMEDRIVE%
而不是 %SystemDrive%
来配合 %HomePath%
。 - gregmac方法一:
#include <Shlobj.h>
std::string desktop_directory(bool path_w)
{
if (path_w == true)
{
WCHAR path[MAX_PATH + 1];
if (SHGetSpecialFolderPathW(HWND_DESKTOP, path, CSIDL_DESKTOPDIRECTORY, FALSE))
{
std::wstring ws(path);
std::string str(ws.begin(), ws.end());
return str;
}
else return NULL;
}
}
方法二:
#include <Shlobj.h>
LPSTR desktop_directory()
{
static char path[MAX_PATH + 1];
if (SHGetSpecialFolderPathA(HWND_DESKTOP, path, CSIDL_DESKTOPDIRECTORY, FALSE)) return path;
else return NULL;
}
nullptr
代替 NULL
。 - Adrian Maire