Unix-Linux編程實踐教程——who

/*--version 1.0--*/
#include <stdio.h>
#include <utmp.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>

#define SHOWHOST
void show_info(utmp *);

int main(){
    utmp current_record;
    int utmpfd;
    int reclen = sizeof(current_record);

    if((utmpfd = open(UTMP_FILE, O_RDONLY)) == -1){
        perror(UTMP_FILE);//e.g. "Error: No such file or directory"
        exit(1);
    }

    while(read(utmpfd, &current_record, reclen) == reclen){
        show_info(&current_record);
    }

    close(utmpfd);
    return 0;
}

void show_info(utmp *utbufp )
{
	/*新的頭文件裏都用宏替代了
	*#define ut_name		ut_user
	*#ifndef _NO_UT_TIME
	*#define ut_time	ut_tv.tv_sec
	*#endif
	*/
	if(utbufp->ut_type != USER_PROCESS)
        return;
    printf("%-8.8s", utbufp->ut_name);  /* the logname  */
    printf(" ");
    printf("%-8.8s", utbufp->ut_line);  /* the tty  */
    printf(" ");
    printf("%10ld", utbufp->ut_time);   /* login time   */
    printf(" ");
#ifdef  SHOWHOST
    printf("(%s)", utbufp->ut_host);    /* the host */
#endif
    printf("\n");               /* newline  */
}

version 2.0 主要就是對空用戶的篩選和對時間格式的修修補補,用到ctime

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章