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");
}