
#include <search.h>
#include <utmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(void)
{
  struct utmp *cur;

  /*   utmpname("/var/log/wtmp"); */
  utmpname("/var/run/utmp");
  hcreate(100);

  while (cur = getutent()) {
    time_t tv = cur->ut_tv.tv_sec;
    char *ctimestr =  ctime(&tv);
    char *nl = strchr(ctimestr, '\n');

    if (nl) *nl ='\0';
    
    if (*cur->ut_user) {
      ENTRY e;

      printf("LOGIN: %s at %s on %s.\n", cur->ut_user, ctimestr, cur->ut_line);
      e.key = cur->ut_line; e.data = cur->ut_user;
      hsearch(e, ENTER);
    } else {
      ENTRY e, *r;
      e.key = cur->ut_line; e.data = cur->ut_user;
      r = hsearch(e, FIND);
      printf("LOGOUT: %s at %s from %s.\n", 
             r ? r->data : "(unknown)", 
             ctimestr, cur->ut_line);
    }
  }
  return 0;
}
