How can I find the user\'s home directory in a cross platform manner in C++? i.e. /home/user in Linux, C:\\Users\\user\\ on Windows Vista, C:\\Documents And Settings\\user\\
This is possible, and the best way to find it is to study the source code of os.path.expanduser("~")
, it is really easy to replicate the same functionality in C.
You'll have to add some #ifdef
directives to cover different systems.
Here are the rules that will provide you the HOME directory
USERPROFILE
or if this fails, concatenate HOMEDRIVE
+HOMEPATH
HOME
or if this fails, use getpwuid() (example code)Important remark: many people are assuming that HOME
environment variable is always available on Unix but this is not true, one good example would be OS X.
On OS X when you run an application from GUI (not console) this will not have this variable set so you need to use the getpwuid().