xref: /plan9-contrib/sys/src/ape/lib/ap/posix/getpwent.c (revision 781103c4074deb8af160e8a0da2742ba6b29dc2b)
1 #include <stdio.h>
2 #include <pwd.h>
3 #include <stdlib.h>
4 
5 static char PASSWD[]	= "/etc/passwd";
6 static FILE *pwf = NULL;
7 static char line[BUFSIZ+2];
8 static struct passwd passwd;
9 
10 void
setpwent(void)11 setpwent(void)
12 {
13 	if( pwf == NULL )
14 		pwf = fopen( PASSWD, "r" );
15 	else
16 		rewind( pwf );
17 }
18 
19 void
endpwent(void)20 endpwent(void)
21 {
22 	if( pwf != NULL ){
23 		fclose( pwf );
24 		pwf = NULL;
25 	}
26 }
27 
28 static char *
pwskip(char * p)29 pwskip(char *p)
30 {
31 	while( *p && *p != ':' && *p != '\n' )
32 		++p;
33 	if( *p ) *p++ = 0;
34 	else p[1] = 0;
35 	return(p);
36 }
37 
38 struct passwd *
pwdecode(char * p)39 pwdecode(char *p)
40 {
41 	passwd.pw_name = p;
42 	p = pwskip(p);
43 	p = pwskip(p); /* passwd */
44 	passwd.pw_uid = atoi(p);
45 	p = pwskip(p);
46 	passwd.pw_gid = atoi(p);
47 	p = pwskip(p); /* comment */
48 	p = pwskip(p); /* gecos */
49 	passwd.pw_dir = p;
50 	p = pwskip(p);
51 	passwd.pw_shell = p;
52 	pwskip(p);
53 	return(&passwd);
54 }
55 
56 struct passwd *
getpwent(void)57 getpwent(void)
58 {
59 	register char *p;
60 
61 	if (pwf == NULL) {
62 		if( (pwf = fopen( PASSWD, "r" )) == NULL )
63 			return(0);
64 	}
65 	p = fgets(line, BUFSIZ, pwf);
66 	if (p==NULL)
67 		return(0);
68 	return pwdecode (p);
69 }
70