How to get a custom home in C (platform independent way)?

How to get a custom home in C (platform independent way)?

I can use getenv("%HOME%") for linux and a similar line on Windows .. but do I need a platform independent way?

+4
source share
3 answers

You can also use getpwuid() on * nix systems if $HOME not installed:

 #include <sys/types.h> #include <pwd.h> #include <stdio.h> int main() { struct passwd *passwdEnt = getpwuid(getuid()); char *home = passwdEnt->pw_dir; printf("home: %s\n", home); return 0; } 
+4
source

This dependent platform . Use #ifdef to select the compiletime method.

 #if defined(_WIN32) // get HOMEDRIVE and HOMEPATH from environment #elif defined(__linux__) // get HOME from environment #else #error Platform not supported yet #endif 
+2
source

It depends on what you want. If you need a valid reason or need to know another user's home directory, use getpwuid_r . Otherwise, getenv("HOME") is the correct way.

+1
source

Source: https://habr.com/ru/post/1343435/


All Articles