How can I find the user's home dir in a cross platform manner, using C++?

前端 未结 3 1425
后悔当初
后悔当初 2020-12-08 01:01

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

3条回答
  •  囚心锁ツ
    2020-12-08 01:34

    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

    • Windows: env USERPROFILE or if this fails, concatenate HOMEDRIVE+HOMEPATH
    • Linux, Unix and OS X: env 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().

提交回复
热议问题