C語言setpwent()函數(shù):從頭讀取密碼文件中的賬號(hào)數(shù)據(jù)
頭文件:
1
|
#include <pwd.h> #include <sys/types.h> |
定義函數(shù):
1
|
void setpwent( void ); |
函數(shù)說明:setpwent()用來將getpwent()的讀寫地址指回密碼文件開頭。
范例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#include <pwd.h> #include <sys/types.h> main() { struct passwd *user; int i; for (i = 0; i < 4; i++) { 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); } setpwent(); 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(); } |
執(zhí)行結(jié)果:
1
2
3
4
5
|
root:0:0:root:/root:/bin/bash bin:1:1:bin:/bin daemon:2:2:daemon:/sbin adm:3:4:adm:/var/adm root:0:0:root:/root:/bin/bash |
C語言getpwent()函數(shù):從密碼文件中取得賬號(hào)的數(shù)據(jù)
頭文件:
1
|
#include <pwd.h> #include <sys/types.h> |
定義函數(shù):
1
|
strcut passwd * getpwent( void ); |
函數(shù)說明:getpwent()用來從密碼文件(/etc/passwd)中讀取一項(xiàng)用戶數(shù)據(jù), 該用戶的數(shù)據(jù)以passwd 結(jié)構(gòu)返回. 第一次調(diào)用時(shí)會(huì)取得第一位用戶數(shù)據(jù), 之后每調(diào)用一次就會(huì)返回下一項(xiàng)數(shù)據(jù), 直到已無任何數(shù)據(jù)時(shí)返回NULL。
passwd 結(jié)構(gòu)定義如下:
1
2
3
4
5
6
7
8
9
10
|
struct passwd { char * pw_name; //用戶賬號(hào) char * pw_passwd; //用戶密碼 uid_t pw_uid; //用戶識(shí)別碼 gid_t pw_gid; //組識(shí)別碼 char * pw_gecos; //用戶全名 char * pw_dir; //家目錄 char * pw_shell; //所使用的shell 路徑 }; |
返回值:返回 passwd 結(jié)構(gòu)數(shù)據(jù), 如果返回NULL 則表示已無數(shù)據(jù), 或有錯(cuò)誤發(fā)生.
附加說明:getpwent()在第一次調(diào)用時(shí)會(huì)打開密碼文件, 讀取數(shù)據(jù)完畢后可使用endpwent()來關(guān)閉該密碼文件。
錯(cuò)誤代碼:
ENOMEM:內(nèi)存不足, 無法配置passwd 結(jié)構(gòu)。
范例
1
2
3
4
5
6
7
8
9
10
11
12
|
#include <pwd.h> #include <sys/types.h> main() { struct passwd *user; while ((user = getpwent()) != 0) { 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(); } |
執(zhí)行:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
root:0:0:root:/root:/bin/bash bin:1:1:bin:/bin: daemon:2:2:daemon:/sbin: adm:3:4:adm:/var/adm: lp:4:7:lp:/var/spool/lpd: sync:5:0:sync:/sbin:/bin/sync shutdown:6:0:shutdown:/sbin:/sbin/shutdown halt:7:0:halt:/sbin:/sbin/halt mail:8:12:mail:/var/spool/mail: news:9:13:news:var/spool/news uucp:10:14:uucp:/var/spool/uucp: operator:11:0:operator :/root: games:12:100:games:/usr/games: gopher:13:30:gopher:/usr/lib/gopher-data: ftp:14:50:FTP User:/home/ftp: nobody:99:99:Nobody:/: xfs:100:101:X Font Server: /etc/Xll/fs:/bin/false gdm:42:42:/home/gdm:/bin/bash kids:500:500: : /home/kids:/bin/bash |
C語言endpwent()函數(shù):關(guān)閉文件(關(guān)閉密碼文件)
頭文件:
1
|
#include <pwd.h> #include <sys/types.h> |
定義函數(shù):
1
|
void endpwent( void ); |
函數(shù)說明:endpwent()用來關(guān)閉由getpwent()所打開的密碼文件。