/etc/passwd
passwd文件保存著用戶的初始工作信息, 每一行保存一位用戶的信息
#include <pwd.h>
struct passwd{
char * pw_name; /* 用戶名*/
char * pw_passwd; /* 密碼 */
uid_t pw_uid; /* 用戶ID */
gid_t pw_gid; /* 組ID */
char * pw_gecos; /* 注釋 */
char * pw_dir; /* 初始工作目錄 */
char * pw_shell; /* 初始shell */
};
//典型的一行信息
root:x:0:0:root:/root:/bin/bash
可以通過getpwuid或getpwnam來獲取指定用戶的信息
struct passwd *getpwuid(uid_t uid); 通過指定uid來獲取
struct passwd *getpwnam(const char *name); 通過指定用戶名來獲取
struct passwd *pwd;
//root的uid為0, 或pwd=getpwnam("root")
if((pwd=getpwuid(0)) ==NULL){
perror("getpuid error");
exit(1);
}else{
printf("name=%s\t",pwd->pw_name);
printf("uid=%u\t",pwd->pw_uid);
printf("gid=%u\n,pwd->pw_gid);
}
除了一次獲取一個(gè)用戶外, 系統(tǒng)還提供了遍歷的方法
struct passwd *ptr;
setpwent(); //打開
while((ptr=getpwent()) !=NULL){ //讀取
... //do something
}
endwent(); //關(guān)閉
/etc/shadow
shadow保存著用戶密碼的相關(guān)信息
#include <shadow.h>
struct spwd {
char *sp_namp; /* 用戶名*/
char *sp_pwdp; /* 加密后的用戶密碼. */
long int sp_lstchg; /* 上次更改密鑰的時(shí)間. */
long int sp_min;
long int sp_max;
long int sp_warn;
long int sp_inact;
long int sp_expire; /* 賬戶到期天數(shù) */
unsigned long int sp_flag;
};
與上一個(gè)的獲取方法類似, 只是shadow結(jié)構(gòu)沒有uid, 所以少了一個(gè)通過uid來獲取的方法
struct spwd *sp;
if((sp=getspnam("root")) ==NULL){
perror("getspnam error");
exit(1);
}else{
printf("name=%s\t",sp->sp_name);
printf("pwdp=%s\n",sp->sp_pwdp);
}
struct spwd *ptr;
setspent(); //打開
while((ptr=getspent()) !=NULL){ //讀取
... //do something
}
endspent(); //關(guān)閉
/etc/group
group文件保存著用戶所屬組的信息
#include <grp.h>
struct group{
char *gr_name;
char *gr_passwd;
int gr_gid;
char *gr_mem;
};
獲取方法同passwd類似, 函數(shù)如下
struct group *getgrgid(gid_t gid);
struct group *getgrnam(const char *name);
struct group *setgrent();
struct group *getgrent();
struct endgrent();
其它
set/get/end三個(gè)組合函數(shù)對下列數(shù)據(jù)文件均適用
d9d40181-3bc6-49b5-aeaa-91f741cfc2d6.png
時(shí)間日期函數(shù)
4c8af49a-7863-4b8e-9ea9-60e34eecbc79.png
ctime/asctime因?yàn)闆]有緩沖大小的設(shè)置已經(jīng)被標(biāo)記為棄用
#include <time.h>
#include <stdio.h>
int main(){
time_t t;
struct tm *tmp;
char buf2[64];
time(&t);
tmp=localtime(&t);
if(strftime(buf2,64,"time and date: %r %a %b %d, %Y",tmp)==0)
printf("strftime failed");
else
printf("%s\n",buf2);
return 0;
}