C語言中操作密碼檔案的一些函數總結_C 語言

來源:互聯網
上載者:User

C語言setpwent()函數:從頭讀取密碼檔案中的帳號資料

標頭檔:

 #include <pwd.h> #include <sys/types.h>

定義函數:

void setpwent(void);

函數說明:setpwent()用來將getpwent()的讀寫地址指回密碼檔案開頭。

範例

#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();}

執行結果:

root:0:0:root:/root:/bin/bashbin:1:1:bin:/bindaemon:2:2:daemon:/sbinadm:3:4:adm:/var/admroot:0:0:root:/root:/bin/bash

C語言getpwent()函數:從密碼檔案中取得帳號的資料

標頭檔:

#include <pwd.h> #include <sys/types.h>

定義函數:

strcut passwd * getpwent(void);

函數說明:getpwent()用來從密碼檔案(/etc/passwd)中讀取一項使用者資料, 該使用者的資料以passwd 結構返回. 第一次調用時會取得第一位使用者資料, 之後每調用一次就會返回下一項資料, 直到已無任何資料時返回NULL。

passwd 結構定義如下:

struct passwd{ char * pw_name; //使用者帳號 char * pw_passwd; //使用者密碼 uid_t pw_uid; //使用者識別碼 gid_t pw_gid; //組識別碼 char * pw_gecos; //使用者全名 char * pw_dir; //家目錄 char * pw_shell; //所使用的shell 路徑};

傳回值:返回 passwd 結構資料, 如果返回NULL 則表示已無資料, 或有錯誤發生.

附加說明:getpwent()在第一次調用時會開啟密碼檔案, 讀取資料完畢後可使用endpwent()來關閉該密碼檔案。

錯誤碼:
ENOMEM:記憶體不足, 無法配置passwd 結構。

範例

#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();}

執行:

root:0:0:root:/root:/bin/bashbin: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/syncshutdown:6:0:shutdown:/sbin:/sbin/shutdownhalt:7:0:halt:/sbin:/sbin/haltmail:8:12:mail:/var/spool/mail:news:9:13:news:var/spool/newsuucp: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/falsegdm:42:42:/home/gdm:/bin/bashkids:500:500: : /home/kids:/bin/bash

C語言endpwent()函數:關閉檔案(關閉密碼檔案)

標頭檔:

#include <pwd.h> #include <sys/types.h>

定義函數:

void endpwent(void);

函數說明:endpwent()用來關閉由getpwent()所開啟的密碼檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.