/*--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, ¤t_record, reclen) == reclen){
show_info(¤t_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
。