开发者

How to get User home in C (platform-independent manner)?

How to get User home in C (platform-independent manner)?

I can use getenv("%HOME%") on linux and similar string on windows.. but I need a plat开发者_StackOverflow中文版form independent manner?


You could also use getpwuid() on *nix systems, if $HOME isn't set:

#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;
}


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

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜