drr*_*lvn 48
getlogin_r()定义的函数unistd.h返回用户名.有关man getlogin_r更多信息,请参阅
它的签名是:
int getlogin_r(char *buf, size_t bufsize);
Run Code Online (Sandbox Code Playgroud)
不用说,这个函数可以很容易地在C或C++中调用.
Nem*_*ric 40
来自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);
}
Run Code Online (Sandbox Code Playgroud)
只需占用主线并将其封装在类中:
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 {};
}
};
Run Code Online (Sandbox Code Playgroud)
仅适用于C:
const char *getUserName()
{
uid_t uid = geteuid();
struct passwd *pw = getpwuid(uid);
if (pw)
{
return pw->pw_name;
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73455 次 |
| 最近记录: |