You have many ways to get user profile directory :
via the environment variable USERPROFILE
:
#include <cstdlib>
...
string profile = getenv("USERPROFILE");
via Windows API, but it is bit harder :
#include <windows.h>
#include <userenv.h>
...
HANDLE processToken = ::GetCurrentProcess();
HANDLE user;
BOOL cr = ::OpenProcessToken(processToken, TOKEN_ALL_ACCESS, &user);
DWORD size = 2;
char * buff = new char[size];
cr = ::GetUserProfileDirectoryA(user, buff, &size); // find necessary size
delete[] buff;
buff = new char[size];
cr = ::GetUserProfileDirectoryA(user, buff, &size);
string profile = buff;
delete[] buff;
and you have to link with userenv.lib
- the tests for return codes are left as an exercise :-)
via ExpandEnvironmentString
:
size = ::ExpandEnvironmentStringsA("%USERPROFILE%\\Desktop\\myfile.anything",
NULL, 2);
buff = new char[size];
size = ::ExpandEnvironmentStringsA("%USERPROFILE%\\Desktop\\myfile.anything",
buff, size);
string profile = buff;
delete[] buff;
With third way you have directly your string, with first and second you only get profile directory and still have to concatenate it with relevant path.
But in fact, if you want you program to be language independant, you should really use SHGetSpecialFolderPath
API function :
#include <shlobj.h>
...
buff = new char[255];
SHGetSpecialFolderPathA(HWND_DESKTOP, buff, CSIDL_DESKTOPDIRECTORY, FALSE);
string desktop = buff;
delete[] buff;
Because on my old XP box in french, Desktop
is actually Bureau
...