getpwnam() 原型如下:
[C++] 纯文本查看 复制代码 #include <sys/types.h>
#include <pwd.h>
struct passwd *getpwnam(const char *name);
参数 name 表示用户名,函数通过这个用户名查找 /etc/passwd 的对应项,如果找到,就将该项信息返回到 struct passwd 结构中,该结构在 pwd.h 中有定义,如下所示:
[C++] 纯文本查看 复制代码 struct passwd {
char *pw_name; /* 用户名 */
char *pw_passwd; /* 用户密码 */
uid_t pw_uid; /* UID */
gid_t pw_gid; /* GID */
char *pw_gecos; /* 用户信息 */
char *pw_dir; /* 用户 home 目录 */
char *pw_shell; /* 使用的 shell 路径 */
};
测试代码:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <pwd.h>
#include <sys/types.h>
int main()
{
struct passwd *user;
user = getpwnam("beyes");
printf ("name: %s\n", user->pw_name);
printf ("uid: %d\n", user->pw_uid);
printf ("gid: %d\n", user->pw_gid);
printf ("user infomation: %s\n", user->pw_gecos);
printf ("user home: %s\n", user->pw_dir);
printf ("user shell: %s\n", user->pw_shell);
return 0;
}
运行输出:./getpwnam
name: beyes
uid: 1000
gid: 100
user infomation: beyes
user home: /home/beyes
user shell: /bin/bash |