《unix高级环境编程》系统数据文件和信息——口令文件

口令文件的结构

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /* The passwd structure.  */  
  2. struct passwd  
  3. {  
  4.   char *pw_name;        /* Username.  */  
  5.   char *pw_passwd;      /* Password.  */  
  6.   uid_t pw_uid;             /* User ID.  */  
  7.   gid_t pw_gid;             /* Group ID.  */  
  8.   char *pw_gecos;       /* Real name.  */  
  9.   char *pw_dir;         /* Home directory.  */  
  10.   char *pw_shell;       /* Shell program.  */  
  11. };  

getpwuid和getpwnam函数

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**** 
  2.  函数功能:获取口令文件信息 
  3.  返回值:若成功返回指针,出错则返回NULL; 
  4.  函数原型: 
  5. *****/  
  6. /* Search for an entry with a matching user ID. */  
  7. struct passwd *getpwuid (uid_t uid);  
  8.   
  9. /* Search for an entry with a matching username. */  
  10. struct passwd *getpwnam (const char *name);  

测试例子:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <pwd.h>  
  2. #include <sys/types.h>  
  3. #include <unistd.h>  
  4. #include "apue.h"  
  5. int main(void)  
  6. {  
  7.     struct passwd *ptr;  
  8.     uid_t ui = getuid();  
  9.     ptr = getpwuid(ui);  
  10.     if(NULL == ptr)  
  11.         perror("error.");  
  12.     printf("pw_name:%s\n",ptr->pw_name);  
  13.     printf("pw_uid:%d\n",ptr->pw_uid);  
  14.     printf("pw_dir:%s\n",ptr->pw_dir);  
  15.   
  16.     exit(0);  
  17. }  

查看口令函数

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /**** 
  2.  * 函数功能:查看整个口令文件信息; 
  3.  * 返回值:若成功则返回指针,若出错或达到文件尾则返回NULL; 
  4.  * 函数原型: 
  5.  * */  
  6. /* Read an entry from the password-file stream, opening it if necessary. */  
  7.  struct passwd *getpwent (void);  
  8.   
  9. /* Rewind the password-file stream. */  
  10.  void setpwent (void);  
  11.   
  12. /* Close the password-file stream. */  
  13.  void endpwent (void);  
例子测试:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #include <pwd.h>  
  2. #include <sys/types.h>  
  3. #include <unistd.h>  
  4. #include "apue.h"  
  5. int main(void)  
  6. {  
  7.     struct passwd *ptr;  
  8.     setpwent();  
  9.     ptr = getpwent();  
  10.     if(NULL == ptr)  
  11.         perror("error.");  
  12.     printf("pw_name:%s\n",ptr->pw_name);  
  13.     printf("pw_uid:%d\n",ptr->pw_uid);  
  14.     printf("pw_dir:%s\n",ptr->pw_dir);  
  15.     endpwent();  
  16.     exit(0);  
  17. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值