ubase

suckless linux base utils
git clone git://git.suckless.org/ubase
Log | Files | Refs | README | LICENSE

last.c (1085B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <errno.h>
      3 #include <libgen.h>
      4 #include <paths.h>
      5 #include <pwd.h>
      6 #include <stdio.h>
      7 #include <stdlib.h>
      8 #include <string.h>
      9 #include <time.h>
     10 #include <utmp.h>
     11 #include <unistd.h>
     12 
     13 #include "config.h"
     14 #include "util.h"
     15 
     16 static void
     17 usage(void)
     18 {
     19 	eprintf("usage: %s [user]\n", argv0);
     20 }
     21 
     22 int
     23 main(int argc, char **argv)
     24 {
     25 	FILE *fp;
     26 	struct utmp ut;
     27 	char *user, *file, *prog;
     28 	time_t t;
     29 
     30 	ARGBEGIN {
     31 	default:
     32 		usage();
     33 	} ARGEND;
     34 
     35 	switch (argc) {
     36 	case 0:
     37 		user = NULL;
     38 		break;
     39 	case 1:
     40 		user = argv[0];
     41 		break;
     42 	default:
     43 		usage();
     44 	}
     45 
     46 	prog = basename(argv0);
     47 	file = (!strcmp(prog, "last")) ? WTMP_PATH : BTMP_PATH;
     48 	if ((fp = fopen(file, "r")) == NULL)
     49 		eprintf("fopen %s:", file);
     50 
     51 	while (fread(&ut, sizeof(ut), 1, fp) == 1) {
     52 		if (ut.ut_type != USER_PROCESS ||
     53 		    (user && strcmp(user, ut.ut_name))) {
     54 			continue;
     55 		}
     56 
     57 		t = ut.ut_time;
     58 		printf("%-8.8s %-8.8s %-16.16s %s",
     59 		       ut.ut_user, ut.ut_line, ut.ut_host, ctime(&t));
     60 	}
     61 	if (fclose(fp))
     62 		eprintf("fclose %s:", file);
     63 	return 0;
     64 }