How to get the current user home directory in Windows

How can I get the path to the user's current home directory?

Example: on Windows, if the current user is "guest", I need "C: \ Users \ guest"

My application will work on most versions of Windows (XP, Vista, Win 7).

+6
source share
4 answers

Use the SHGetFolderPath function. This function is preferable to querying environment variables, as the latter can be modified to indicate the wrong location. The documentation provides an example that I am repeating 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))) { ... } 
+11
source

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

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

+5
source

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

+1
source

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
source

Source: https://habr.com/ru/post/909866/


All Articles