1.getpwuid()函数
通过用户uid查找用户的相关信息,并以passwd的结构体返回其数据. 头文件:#include <sys/types.h> #include <pwd.h> 函数原型:struct passwd *getpwuid(uid_t uid); 参数 文件所有者的uid; 返回值:成功passwd 结构体,uid所对应的用户信息,错误返回空指针, struct passwd { char * pw_name; /* Username, POSIX.1 */ char * pw_passwd; /* Password */ __uid_t pw_uid; /* User ID, POSIX.1 */ __gid_t pw_gid; /* Group ID, POSIX.1 */ char * pw_gecos; /* Real Name or Comment field */ char * pw_dir; /* Home directory, POSIX.1 */ char * pw_shell; /* Shell Program, POSIX.1 */ }
2.getgrgid()函数
通过gid,找到该组的相关信息,并以group结构体返回其信息, 头文件:#include <grp.h>,#include <sys/types.h> 参数 文件所属组的组id; 返回值:成功返回group结构体,错误返回NULL; group结构体: struct group { char *gr_name; /*组名称*/ char *gr_passwd; /* 组密码*/ gid_t gr_gid; /*组识别码*/ char **gr_mem; /*组成员账号*/ } 看个例子:
#include <stdio.h> #include <stdlib.h> #include <pwd.h> #include <grp.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> void my_err(const char *err_string,int line) { fprintf(stderr,"line:%d",line); perror(err_string); exit(1); } int main(int argc,char *argv[]) { struct stat buf; struct passwd *my_info; struct group *grp; if(stat(argv[1],&buf)==-1) my_err("stat",__LINE__); my_info=getpwuid(buf.st_uid); grp=getgrgid(buf.st_gid); printf("文件所有者的信息"); printf( "my name = [%s]\n", my_info->pw_name ); printf( "my passwd = [%s]\n", my_info->pw_passwd ); printf( "my uid = [%d]\n", my_info->pw_uid ); printf( "my gid = [%d]\n", my_info->pw_gid ); printf( "my gecos = [%s]\n", my_info->pw_gecos); printf( "my dir = [%s]\n", my_info->pw_dir ); printf( "my shell = [%s]\n", my_info->pw_shell ); printf("文件所属组的信息:"); printf("group name =[%s]\n",grp->gr_name); printf("group passwd = [%s]\n",grp->gr_passwd); printf("组识别码 = [%d]\n",grp->gr_gid); printf("组成员账号 = [%s]\n",*(grp->gr_mem)); }
结果:
yang@liu:~/Linux C$ gcc getpwuid.c yang@liu:~/Linux C$ ./a.out fork.c 文件所有者的信息my name = [yang] my passwd = [x] my uid = [1000] my gid = [1000] my gecos = [yang,,,] my dir = [/home/yang] my shell = [/bin/bash] 文件所属组的信息:group name =[yang] group passwd = [x] 组识别码 = [1000] 组成员账号 = [(null)]