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

getpwnam函数
给出用户登录名,获取口令文件项

#include <pwd.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>

struct passwd *getpwnam(const char *name)
{
    struct passwd *ptr;

    /*
      void setpwent(void)
      反绕所使用的文件
    */
    setpwent();

    /*
      struct passwd *getpwent(void);
      返回口令文件中的下一个记录项
    */
    while((ptr = getpwent()) != NULL)
    {
        /* found a match */
        if(strcmp(name, ptr->pw_name) == 0)
            break;   
    }

    /*
       void endpwent(void)
       关闭所使用的文件
    */
    endpwent();
    return (ptr);  /* ptr is NULL if no match found */
}

int main(int argc, char *argv[])
{
    if(argc != 2)
        printf("usage: ./getpwnam <name>");
    char *name = argv[1];
    struct passwd *ptr = getpwnam(name);
    printf("name: %s\n", ptr->pw_name);
    printf("passwd: %s\n", ptr->pw_passwd);
    printf("uid: %d\n", ptr->pw_uid);
    printf("gid: %d\n", ptr->pw_gid);
    printf("dir: %s\n", ptr->pw_dir);
    printf("shell: %s\n", ptr->pw_shell);
    return 0;
}

这里写图片描述

开始调用setpwent是自我保护性的措施,以便在调用者在此之前已经调用getpwent打开了有关文件的情况下,反绕有关
文件使它们定位到文件开始处。getpwnam和getpwuid调用完成后不应使有关文件仍处于打开状态,所以应调用endpwent关闭它们。

打印时间

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    /*
           存放自1970年1月1日0点0时0分开始的秒数
    */
    time_t t;

    /*
       struct tm
       {
        int tm_sec;   [0-60]
        int tm_min;   [0-59]
        int tm_hour;  [0-23]
        int tm_mday;  [1-31]
        int tm_mon;   [0-11]
        int tm_year;  years since 1900
        int tm_wday;  [0-6]
        int tm_yday;  [0-365]
        int tm_isdst; 
       }
    */
    struct tm *tmp;
    char buf1[16];
    char buf2[64];64,

    /*
       time_t time(time_t *calptr);
       返回时间值
       如果参数不为空,时间值页存放在calptr指向的单元
    */
    time(&t);

    /*
      struct tm *localtime(const time_t *calptr);
      将日历时间转换为本地时间,考虑本地时区和夏时制标志
    */
    tmp = localtime(&t);

    /*
      size_t strftime(char *restrict buf, size_t maxsize, 
              const char *restrict format, 
              const struct tm *restrict tmptr);
      打印时间值
      返回:若有口昂就则返回存入数组的字符数,否则返回0
          %r 本地时间:(12时制) 06:27:38 PM
      %a 缩写的周日名   Tue
      %b 缩写的月名  Feb
      %d 月日:[01-31]  10
      %Y 年 2004
    */
    if(strftime(buf1, 16, "time and date: %r, %a %b %d, %Y", tmp) == 0)
        printf("buffer length 16 is to small\n");
    else
        printf("%s\n", buf1);
    if(strftime(buf2, 64, "time and date: %r, %a %b %d, %Y", tmp) == 0)
        printf("buffer length 64 is too small\n");
    else
        printf("%s\n", buf2);
    exit(0);
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/u012319493/article/details/80377602