Linux getpw、getpwend、setpwent和endpwent函数

    xiaoxiao2021-12-01  22

    getpw、getpwend、setpwent和endpwent

    头文件

    1. #include <pwd.h>     #include <sys/types.h>     #define _GNU_SOURCE 2. #incldue <pwd.h>     #include <sys/types.h> 3. #include <pwd.h>     #include <sys/types.h> 4. #include <pwd.h>     #include <sys/types.h>  

    函数原型

    int getpw(uid_t uid, char *buf);

    struct passwd *getpwent(void);

    void setpwent(void);

    void endpwent(void);

    功能

    getpw函数取得uid_t为uid的用户的密码文件的相关数据。 getpwent函数返回下一条记录项,此记录项是一个由它填写好的password结构的指针。 setpwent函数能从密码文件中取得帐号的数据,setpwent()用来将getpwent()的读写地址指回密码文件开头 endpwent函数一般用来关闭用getpwent打开的密码文件。

    参数

    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的路径*/ };

    例子

    getpw

    #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> int main() { char buffer[80]; getpw(0, buffer); printf("%s\n", buffer); exit(0); }

    getpwent和endpwent

    #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pwd.h> #include <unistd.h> int main(void) { 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(); exit(0); }

    来自unix环境高级编程的例子

    #include <pwd.h> /*getpwnam函数的实现*/ #include <stddef.h> #include <string.h> #include <sys/types.h> struct passwd *getpwnam(const char *name) { struct passwd *ptr; setpwent(); while((ptr = getpwent()) != NULL) { if(strcmp(name, ptr->pw_name) == 0) { break; } } endpwent(); return(ptr); }
    转载请注明原文地址: https://ju.6miu.com/read-679332.html

    最新回复(0)