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

前端 未结 3 1440
后悔当初
后悔当初 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:08

    I don't think it's possible to completely hide the Windows/Unix divide with this one (unless, maybe, Boost has something).

    The most portable way would have to be getenv("HOME") on Unix and concatenating the results of getenv("HOMEDRIVE") and getenv("HOMEPATH") on Windows.

    const static volatile char A = 'a'; // All this is to prevent reverse engineering
    #ifdef unix
        HomeDirectory = getenv((char[]){A-25, A-18, A-20, A-28, 0});
    #elif defined(_WIN32)
        HomeDirectory = getenv((char[]){A-25, A-18, A-20, A-28, A-29, A-15, A-24, A-11, A-28, 0});
        const char*Homepath = getenv((char[]){A-25, A-18, A-20, A-28, A-17, A-32, A-13, A-25, 0});
        HomeDirectory = malloc(strlen(HomeDirectory)+strlen(Homepath)+1);
        strcat(HomeDirectory, Homepath);
    #endif
    

提交回复
热议问题