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

口令文件的结构

/* The passwd structure.  */
struct passwd
{
  char *pw_name;		/* Username.  */
  char *pw_passwd;		/* Password.  */
  uid_t pw_uid;		        /* User ID.  */
  gid_t pw_gid;		        /* Group ID.  */
  char *pw_gecos;		/* Real name.  */
  char *pw_dir;			/* Home directory.  */
  char *pw_shell;		/* Shell program.  */
};

getpwuid和getpwnam函数

/****
 函数功能:获取口令文件信息
 返回值:若成功返回指针,出错则返回NULL;
 函数原型:
*****/
/* Search for an entry with a matching user ID. */
struct passwd *getpwuid (uid_t uid);

/* Search for an entry with a matching username. */
struct passwd *getpwnam (const char *name);

测试例子:

#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include "apue.h"
int main(void)
{
    struct passwd *ptr;
    uid_t ui = getuid();
    ptr = getpwuid(ui);
    if(NULL == ptr)
        perror("error.");
    printf("pw_name:%s\n",ptr->pw_name);
    printf("pw_uid:%d\n",ptr->pw_uid);
    printf("pw_dir:%s\n",ptr->pw_dir);

    exit(0);
}

查看口令函数

/****
 * 函数功能:查看整个口令文件信息;
 * 返回值:若成功则返回指针,若出错或达到文件尾则返回NULL;
 * 函数原型:
 * */
/* Read an entry from the password-file stream, opening it if necessary. */
 struct passwd *getpwent (void);

/* Rewind the password-file stream. */
 void setpwent (void);

/* Close the password-file stream. */
 void endpwent (void);
例子测试:

#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include "apue.h"
int main(void)
{
    struct passwd *ptr;
    setpwent();
    ptr = getpwent();
    if(NULL == ptr)
        perror("error.");
    printf("pw_name:%s\n",ptr->pw_name);
    printf("pw_uid:%d\n",ptr->pw_uid);
    printf("pw_dir:%s\n",ptr->pw_dir);
    endpwent();
    exit(0);
}

参考资料:

《unix高级环境编程》

你可能感兴趣的:(口令文件,Unix高级环境编程)