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 will run on most of the Windows versions (XP, Vista, Win 7).
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 will run on most of the Windows versions (XP, Vista, Win 7).
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))) {
...
}
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
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;
}