编写who命令-第2版

【编写who命令-第2版】之前写过第1版who命令:
https://www.jianshu.com/p/ac7dce45bd95
缓冲是提高文件I/O效率的方法之一,现在运用缓冲技术写第2版who命令:
分为2个文件utmplib.c和who2.c,who2.c把前一个文件include进来即可。
下面是utmplib.c:

#include #include #include #include #include #include #include #include #define UTMP_SIZE (sizeof(struct utmp)) #define NUM 3int fd = -1; int cur_utmp = 0; int num_utmp = 0; char utmpbuf[NUM * UTMP_SIZE]; void utmp_open(char *filename) { if((fd = open(filename, O_RDONLY)) == -1) { printf("Can't open file %s\n", filename); exit(1); } }int utmp_load() { int res = read(fd, utmpbuf, NUM * UTMP_SIZE); num_utmp = res/UTMP_SIZE; cur_utmp = 0; return num_utmp; }struct utmp * utmp_next() { if (cur_utmp == num_utmp && utmp_load() == 0) { return (struct utmp *)NULL; } return (struct utmp *)&utmpbuf[(cur_utmp++)*UTMP_SIZE]; }void utmp_close() { if (fd != -1) { close(fd); } }void show_time(time_t t) { struct tm *tt = localtime(&t); printf("%d-%02d-%02d %02d:%02d", tt->tm_year+1900, tt->tm_mon+1, tt->tm_mday, tt->tm_hour, tt->tm_min); }void show_info(struct utmp *record) { if (record->ut_type != USER_PROCESS) return; printf("%-8s", record->ut_user); printf(" "); printf("%-12s", record->ut_line); printf(" "); show_time(record->ut_tv.tv_sec); printf(" "); printf("(%s)", record->ut_host); printf("\n"); }

下面是who2.c:
#include #include #include #include #include #include #include #include #include "utmplib.c"int main() { utmp_open("/var/run/utmp"); struct utmp *utmp_record; while ((utmp_record=utmp_next()) != (struct utmp *)NULL) { show_info(utmp_record); } utmp_close(); return 0; }

    推荐阅读