如何在 Linux 中获取 C/C++ 中的用户名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8953424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the username in C/C++ in Linux?
提问by Zat42
How can I get the actual "username" without using the environment (getenv, ...) in a program?
如何在不使用程序中的环境(getenv,...)的情况下获取实际的“用户名”?
采纳答案by drrlvn
The function getlogin_r()
defined in unistd.h
returns the username. See man getlogin_r
for more information.
中getlogin_r()
定义的函数unistd.h
返回用户名。有关man getlogin_r
更多信息,请参阅。
Its signature is:
它的签名是:
int getlogin_r(char *buf, size_t bufsize);
Needless to say, this function can just as easily be called in C or C++.
不用说,这个函数可以很容易地在 C 或 C++ 中调用。
回答by Nemanja Boric
From http://www.unix.com/programming/21041-getting-username-c-program-unix.html:
从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);
}
Just take main lines and encapsulate it in class:
只需将主线封装在类中即可:
class Env{
public:
static std::string getUserName()
{
uid_t uid = geteuid ();
struct passwd *pw = getpwuid (uid);
if (pw)
{
return std::string(pw->pw_name);
}
return {};
}
};
For C only:
仅适用于 C:
const char *getUserName()
{
uid_t uid = geteuid();
struct passwd *pw = getpwuid(uid);
if (pw)
{
return pw->pw_name;
}
return "";
}