• 简单实现getpwnam()


    利用getpwent 、setpwent、endpwent来实现getpwnam的功能。

    #include<pwd.h>

    struct pwd *getpwnam(const char *name)   return pointers on success ,or NULL on error

    getpwnam()通过输入的用户名来返回指向struct pwd结构的指针,struct pwd 结构内容与/etc/passwd的7项内容相对应。可以通过man getpwnam 来

    具体查看struct pwd 中每一项的内容。

    #include <pwd.h>

    struct pwd *getpwent(void)   return pointers on success ,or NULL on end of stream or error

    void setpwent(void);

    void endpwent();

    getpwent()函数一旦调用会自动打开密码文件(/etc/passwd),当密码文件处理完毕后,要使用endpwent()将其关闭。

    在使用的过程中,调用setpwent()可以重新返回文件的起始处。

     1   1 #include "head.h"
     2   2
     3   3 
     4   4 struct passwd *getpwnam(const char *name)
     5   5 {
     6   6       struct passwd *ptr;
     7   7       //setpwent();  
     8   8       while((ptr = getpwent())!=NULL)
     9   9             if(strcmp(name,ptr->pw_name)==0)
    10  10                      break;
    11  11       endpwent();
    12  12       return(ptr);
    13  13 }
    14  14 int main (int argc,char *argv[])
    15  15 {
    16  16         struct passwd *pwd;
    17  17         char name[20]={"zhengyu"};
    18  18         printf("enter the name which you want to find
    ");
    19  19         scanf("%s",name);
    20  20         getchar();
    21  21         pwd=getpwnam(name);
    22  22         printf("user id is %d
    ",pwd->pw_uid);
    23  23         printf("user name is %s
    ",pwd->pw_name);
    24  24         printf("user group id is %d
    ",pwd->pw_gid);
    25  25         printf("user directory is %s
    ",pwd->pw_dir);
    26  26         printf("user login shell is %s
    ",pwd->pw_shell);
    27  27         return 0;
    28  28 
    29  29 }

    head.h

      1 #include <sys/uio.h>
      2 #include <sys/types.h>
      3 #include <sys/stat.h>
      4 #include <unistd.h>
      5 #include <stdlib.h>
      6 #include <stdio.h>
      7 #include <string.h>
      8 #include <fcntl.h>
      9 #include <errno.h>
     10 #include <setjmp.h>
     11 #include <pwd.h>
     12 #include <grp.h>
     13 #include <limits.h>
     14 #include <shadow.h>
                              

    在使用此类返回NULL时不一定是出错的函数时,可以通过设置errno的值来使用。

    1     errno=0;
    2     if(pwd==NULL)       
    3     {
    4             if(errno==0)
    5             printf("deal...");
    6             else
    7             perror("error");
    8      }
  • 相关阅读:
    cvLoadImage cvCreateImage函数使用方法
    CString 的FindOneOf
    FTP与SFTP的区别
    如何在Linux环境下编译lib 库
    CString 和 string之间的转换
    Cstring getlength
    CString类常用方法----Left(),Mid(),Right()……
    LPCTSTR
    明白fopen的参数r+,w+以及a+
    libsvm -c http://www.ilovematlab.cn/thread-89155-1-1.html
  • 原文地址:https://www.cnblogs.com/zydark/p/7731364.html
Copyright © 2020-2023  润新知