编写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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值