- switch(argc) {
- case 2:
- fname = argv[1];
- break;
- case 3:
- if (!(tp = ttyname(0))) {
- /*
- * no tty -- use best guess from passwd file.
- * next line is a kludge, but as of now getuid
- * returns a "uid_t" and getpwuid takes an int.
- */
- pw = getpwuid((int)getuid());
- strncpy(utmp.ut_name,pw ? pw->pw_name : "?",NMAX);
- strcpy(utmp.ut_line,"tty??");
- time(&utmp.ut_time);
- putline();
- exit(0);
- }
- tp = rindex(tp,'/') + 1;
- if (gethostname(hostname,sizeof(hostname)) == -1) {
- perror("gethostname");
- exit(1);
- }
- case 1:
- fname = "/etc/utmp";
- break;
- default:
- fputs("usage: who [ utmp_file ]\nor who am i\n",stderr);
- exit(1);
- }
- if (!(fp = fopen(fname,"r"))) {
- perror(fname);
+ switch (argc) {
+ case 1: /* who */
+ ufp = file(_PATH_UTMP);
+ /* only entries with both name and line fields */
+ while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1)
+ if (*usr.ut_name && *usr.ut_line)
+ output(&usr);
+ break;
+ case 2: /* who utmp_file */
+ ufp = file(argv[1]);
+ /* all entries */
+ while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1)
+ output(&usr);
+ break;
+ case 3: /* who am i */
+ ufp = file(_PATH_UTMP);
+
+ /* search through the utmp and find an entry for this tty */
+ if (p = ttyname(0)) {
+ /* strip any directory component */
+ if (t = rindex(p, '/'))
+ p = t + 1;
+ while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1)
+ if (usr.ut_name && !strcmp(usr.ut_line, p)) {
+ output(&usr);
+ exit(0);
+ }
+ /* well, at least we know what the tty is */
+ (void)strncpy(usr.ut_line, p, UT_LINESIZE);
+ } else
+ (void)strcpy(usr.ut_line, "tty??");
+ pw = getpwuid(getuid());
+ (void)strncpy(usr.ut_name, pw ? pw->pw_name : "?", UT_NAMESIZE);
+ (void)time(&usr.ut_time);
+ *usr.ut_host = '\0';
+ output(&usr);
+ break;
+ default:
+ (void)fprintf(stderr, "usage: who [ file ]\n who am i\n");