简体   繁体   English

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

[英]How to get the current user's home directory in Windows

How can I get the path to the current User's home directory? 如何获取当前用户主目录的路径?

Ex: In Windows, if the current user is "guest" I need "C:\\Users\\guest" 例如:在Windows中,如果当前用户是“访客”,我需要“C:\\ Users \\ guest”

My application will run on most of the Windows versions (XP, Vista, Win 7). 我的应用程序将在大多数Windows版本(XP,Vista,Win 7)上运行。

Use the function SHGetFolderPath . 使用函数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))) {
  ...
}

Just use the environment variables, in this particular case you want %HOMEPATH% and combine that with %SystemDrive% 只需使用环境变量,在这种特殊情况下,您需要%HOMEPATH%并将其与%SystemDrive%结合使用

http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

我使用%USERPROFILE%来获取当前用户主目录的路径。

Approach 1: 方法1:

#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;
    }
}

Approach 2: 方法2:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM