home *** CD-ROM | disk | FTP | other *** search
- /* which.c - tell which program is executed when you type it's name */
- /* usage: which command [command]... */
- /* fixes bug in earlier version using turbo-C searchpath() */
- /* should be completely portable now */
-
- #include <stdio.h>
- #define lerror( str ) { fputs( str, stderr ); _exit(1); }
- #define EXIST(s) (modtime(s) !=0)
-
- static char *h="$header: which.c ver 8 Matt Cohen size 2725 time 4/27/88 23:01:08$";
- static char *c="$copyright: (c) 1988 Matt Cohen$";
-
- main(argc,argv)
- int argc; char *argv[];
- {
- char *searchpath(), buf[BUFSIZ], *pathname, *strcpy();
- int i,flag=0; long modtime();
-
- if (argc < 2) lerror("usage: which command [command]...\n");
- for(i=1; i < argc; i++) {
- flag=0;
- strcpy(buf,argv[i]);
- pathname=searchpath(buf);
- flag=(pathname != NULL);
- if (flag) printf("%s\n",pathname);
- else printf("%s not found\n",argv[i]);
- }
- }
-
- /* make full filename fn have suffix s */
- suffix(fn,q)
- char fn[],q[];
- { int k; int i;
- for(k=0; k < strlen(fn) && fn[k] != '.'; k++);
- if (k == strlen(fn)) fn[k]='.';
- k++;
- fn[k]='\0';
- strcat(fn,q);
- }
-
- /* search the path for the program s , looking first in . */
- char *searchpath(s)
- char *s ;
- { char *B[20]; int i,n; char *getenv(), *path, *strsave(), *strcpy();
- char f[50], dir[50];
- long modtime();
- /* look in . first */
-
- suffix(s,"COM");
- if (EXIST(s)) return(strsave(s));
- suffix(s,"EXE");
- if (EXIST(s)) return(strsave(s));
- suffix(s,"BAT");
- if (EXIST(s)) return(strsave(s));
- /* now look through path */
- if ((path=getenv("PATH"))==NULL) return(NULL); /* no path */
- n=split(path,B);
- for(i=0; i<n; i++)
- {
- strcpy(dir,B[i]); strcat(dir,"\\");
- strcat(dir,s);
- suffix(dir,"COM");
- if (EXIST(dir)) return(strsave(dir));
- suffix(dir,"EXE");
- if (EXIST(dir)) return(strsave(dir));
- suffix(dir,"BAT");
- if (EXIST(dir)) return(strsave(dir));
- }
- return(NULL);
- }
-
- /* split path into array B[] with n elts */
- split(path,B)
- char *path;
- char *B[];
- {
- int i=0; char *strtok(),*strsave(),*p, *tok;
- p = strsave(path);
- tok = strtok(p,";");
- B[i++] = strsave(tok);
- while(tok != NULL)
- {
- tok = strtok(NULL,";");
- if (tok != NULL)
- B[i++] = strsave(tok);
- }
- return(i);
- }
-
- /* strsave - save string s somewhere; return address */
- char *strsave(s)
- char *s;
- {
- char *malloc(), *p, *strcpy();
- p = malloc(strlen(s)+1); /* +1 to hold '\0' */
- if (p==NULL) {
- fprintf(stderr,"out of memory\n"); exit(1); }
- return(strcpy(p, s));
- }
-
- #define TIME_TYPE long
- #include <sys/stat.h>
- /* modtime - return file's modification time (0 for nonexistent files) */
- TIME_TYPE modtime(file)
- char *file;
- {
- struct stat buf;
- return(stat(file, &buf) >= 0 ? buf.st_mtime : 0);
- }
-