From: Ben Cox (thoth@uiuc.edu)
Date: 07/06/92


From: thoth@uiuc.edu (Ben Cox)
Subject: Re: Where is which?
Date: 7 Jul 1992 01:42:09 GMT


>>>Where can I find 'which' as mentioned in the GCC installation?
>>>Thanks in advance,

Here is a which.c that I hacked together. Anyone may copy it for any
reason whatsoever. Hell, you can even sell it without putting my name
on it. (It's not very good, so I'd rather you didn't put my name one
it...) :^>

#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>

#define ELEMSZ 1024

static void lookfor(char *command, char *path)
{
  char elem[ELEMSZ];
  char *i;
  int done = 0, found = 0, l;
  struct stat fileinfo;
  char *o_path = path;

  while ( !done ) {
    i = strchr(path, ':');
    if ( i == (char *) NULL ) {
      strcpy(elem, path);
      done = 1;
    } else {
      l = i - path;
      strncpy(elem, path, l);
      elem[l] = '\0';
      path = i + 1;
    }
    l = strlen(elem);
    if ( l == 0 || elem[l - 1] != '/' ) strcat(elem, "/");
    strcat(elem, command);
    if ( !access(elem, 0) ) {
      if ( !stat(elem, &fileinfo) ) {
        int dm = ( S_IFREG | S_IXUSR );
        if ( (fileinfo.st_mode & dm) == dm ) {
          puts(elem);
          done = found = 1;
        }
      }
    }
  }
  if ( !found ) {
    fprintf(stderr, "no %s in %s\n", command, o_path);
    exit(2);
  }
}

main(int argc, char *argv[], char *envp[])
{
  char *envel;
  int i;

  if ( argc != 2 ) {
    fprintf(stderr, "Usage: %s command\n", argv[0]);
    exit(1);
  }

  for ( envel = envp[i = 0]; envel; envel = envp[++i] ) {
    if ( !strncmp(envel, "PATH=", 5) ) {
      lookfor(argv[1], envel + 5);
      exit(0);
    }
  }
  fprintf(stderr, "%s: no PATH variable.\n", argv[0]);
  exit(3);
}