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

前端 未结 4 1824
野的像风
野的像风 2020-12-18 00:29

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\"

My application wil

相关标签:
4条回答
  • 2020-12-18 01:08

    Just use the environment variables, in this particular case you want %HOMEPATH% and combine that with %SystemDrive%

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

    0 讨论(0)
  • 2020-12-18 01:12

    Approach 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:

    #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;
    }
    
    0 讨论(0)
  • 2020-12-18 01:16

    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))) {
      ...
    }
    
    0 讨论(0)
  • 2020-12-18 01:25

    I have used %USERPROFILE% to get path the current User's home directory.

    0 讨论(0)
提交回复
热议问题