如何在Linux中获取C / C ++的用户名?

如何在程序中不使用环境(getenv,…)的情况下获得实际的“用户名”?

Solutions Collecting From Web of "如何在Linux中获取C / C ++的用户名?"

unistd.h定义的函数getlogin_r()返回用户名。 有关更多信息,请参阅man getlogin_r

其签名是:

 int getlogin_r(char *buf, size_t bufsize); 

不用说,这个函数可以在C或C ++中轻松调用。

http://www.unix.com/programming/21041-getting-username-c-program-unix.html

 /* whoami.c */ #define _PROGRAM_NAME "whoami" #include <stdlib.h> #include <pwd.h> #include <stdio.h> int main(int argc, char *argv[]) { register struct passwd *pw; register uid_t uid; int c; uid = geteuid (); pw = getpwuid (uid); if (pw) { puts (pw->pw_name); exit (EXIT_SUCCESS); } fprintf (stderr,"%s: cannot find username for UID %u\n", _PROGRAM_NAME, (unsigned) uid); exit (EXIT_FAILURE); } 

只要采取主线并将其封装在课堂上:

 class Env{ public: static std::string getUserName() { register struct passwd *pw; register uid_t uid; int c; uid = geteuid (); pw = getpwuid (uid); if (pw) { return std::string(pw->pw_name); } return std::string(""); } }; 

仅限C:

 const char *getUserName() { uid_t uid = geteuid(); struct passwd *pw = getpwuid(uid); if (pw) { return pw->pw_name; } return ""; }