編寫who命令

Refer:編寫who命令

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

#define SHOWHOST

void show_info(struct utmp*);
int main(){
    struct utmp record;
    FILE *fp;
    int strulen=sizeof(record);
    if((fp=fopen("/var/run/utmp","r"))==0){ //打開文件
        perror("fopen");
        exit(0);
    }
    memset(&record,0x00,strulen);
    while(fread(&record,strulen,1,fp)){ //循環讀取記錄(結構體)
        show_info(&record);
    }
    fclose(fp); //關閉文件
    return 0;
}
void show_info(struct utmp *buf){
    if(buf->ut_type!=USER_PROCESS) //非登錄用戶
        return;
    printf("%-8s ",buf->ut_name); //輸出用戶名
    printf("%-12s ",buf->ut_line); //終端設備名
    time_t timelong=buf->ut_time;
    struct tm *localnow=localtime(&timelong);
    printf("%04d-%02d-%02d %02d:%02d ",localnow->tm_year+1900,localnow->tm_mon+1,localnow->tm_mday,localnow->tm_hour,localnow->tm_min); //登錄時間
    #ifdef SHOWHOST
        printf("(%s)",buf->ut_host);
    #endif
    printf("\n");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章