<strong><span style="color:#ff6666;">扫描密码文件和组文件中的所有记录</span></strong>
函数setpwent(),getpwent()和endpwent()的作用是按顺序扫描密码文件中的记录。
#include <sys/types.h>
#include <pwd.h>
struct passwd *getpwent(void);
void setpwent(void);
void endpwent(void);
getpwent()能够从密码文件中逐条返回记录,如果不再有返回记录或者出错时,则返回NULL。getpwent一经
调用会自动打开密码文件。当密码文件处理完毕后,可调用endpwent()将其关闭。
The passwd structure is defined in <pwd.h> as follows:
struct passwd {
char *pw_name; /* username */
char *pw_passwd; /* user password */
uid_t pw_uid; /* user ID */
gid_t pw_gid; /* group ID */
char *pw_gecos; /* user information */
char *pw_dir; /* home directory */
char *pw_shell; /* shell program */
};
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <pwd.h>
5 int main()
6 {
7 struct passwd *pwd;
8 while((pwd = getpwent())!=NULL)
9 {
10 printf("%-8s %5ld\n",pwd->pw_name,(long)pwd->pw_uid);
11 }
12 endpwent();
13 }
songxl@ubuntu:~/ds/day04$ a.out
root 0
daemon 1
bin 2
sys 3
sync 4
games 5
man 6
lp 7
mail 8
news 9
uucp 10
proxy 13
www-data 33
backup 34
list 38
irc 39
gnats 41
nobody 65534
libuuid 100