您的位置:首页 > 其它

编写who命令

2015-05-07 16:19 302 查看
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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  命令 who