getpwent() 函数原型如下:
[C++] 纯文本查看 复制代码 #include <sys/types.h>
#include <pwd.h>
struct passwd *getpwent(void);
getpwent() 从 /etc/passwd 中读取一项数据,然后返回到 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 路径 */
};
可以循环调用该函数,而依次获得各项数据,知道无任何数据可读时函数返回 NULL 。
测试代码:
[C++] 纯文本查看 复制代码 #include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
int main()
{
struct passwd *user;
while ((user = getpwent()))
printf ("%s:%d:%d:%s:%s:%s\n", user->pw_name, user->pw_uid,
user->pw_gid, user->pw_gecos, user->pw_dir, user->pw_shell);
endpwent();
return 0;
}
运行输出效果相当于执行命令:cat /etc/passwd 。 |