home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Usenet 1994 October
/
usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso
/
unix
/
volume14
/
bsd-dyna-link
/
which.c
< prev
Wrap
C/C++ Source or Header
|
1988-05-08
|
2KB
|
100 lines
#include <sys/param.h>
#include <sys/stat.h>
/* This does the equivalent of /bin/which. That is, given a filename,
** it searches directories named in the environment variable PATH, until
** it finds a file with that filename.
*/
#define copy_of(name) ((char*) sprintf(malloc(strlen(name)+1), "%s", name))
static
exists(filename)
char* filename;
{
struct stat buffer;
return(stat(filename, &buffer) != -1);
}
/* The PATH string looks something like this:
**
** .:/u/djones/bin:/usr/local/bin:/usr/mega/bin:/u/mega/bin
**
**
** except probably longer.
*/
char*
which(file)
char* file;
{
if(*file == '/') return copy_of(file);
{ char* search = (char*)getenv("PATH");
if(search == 0)
search = ".:~/bin:/usr/mega/bin:/usr/local/bin:/usr/new:/usr/ucb:/usr/bin:/bin:/usr/hosts:/usr/games";
{ register char* ptr = search;
while(*ptr)
{ char name[MAXPATHLEN];
register char* next = name;
/* copy directory name into [name] */
while(*ptr && *ptr != ':') *next++ = *ptr++;
if(*ptr) ptr++;
*next++ = '/'; /* separates directory name and filename */
/* copy filename into [name] */
{ register char* ptr2 = file;
while(*ptr2) *next++ = *ptr2++;
}
*next = '\0';
{ char* afile = (char*)(name);
if(exists(afile)) return (afile);
free(afile);
}
}
}
return file;
}
}
#undef binwhich
#ifdef binwhich
main(argc, argv)
char** argv;
{
argc--; argv++;
while (argc)
{ char* path = which(*argv);
if(path)
{
printf("%s\n", path);
free(path);
}
else
{ char* ptr = search;
printf("no %s in ", *argv);
while(*ptr)
{ putchar(*ptr==':' ? ' ' : *ptr);
ptr++;
}
putchar('\n');
}
argc--; argv++;
}
exit(0);
}
#endif binwhich