home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume14 / bsd-dyna-link / which.c < prev   
C/C++ Source or Header  |  1988-05-08  |  2KB  |  100 lines

  1. #include <sys/param.h>
  2. #include <sys/stat.h>
  3.  
  4.  
  5. /* This does the equivalent of /bin/which.  That is, given a filename,
  6. ** it searches directories named in the environment variable PATH, until
  7. ** it finds a file with that filename.
  8. */
  9. #define copy_of(name) ((char*) sprintf(malloc(strlen(name)+1), "%s", name))
  10.  
  11. static
  12. exists(filename)
  13.   char* filename;
  14. {
  15.   struct stat buffer;
  16.   return(stat(filename, &buffer) != -1);
  17.  
  18. }
  19.  
  20. /* The PATH string looks something like this:
  21. **
  22. ** .:/u/djones/bin:/usr/local/bin:/usr/mega/bin:/u/mega/bin
  23. **
  24. **
  25. ** except probably longer.
  26. */
  27.  
  28. char*
  29. which(file)
  30.   char* file;
  31. {
  32.  
  33.   if(*file == '/') return copy_of(file);
  34.  
  35.   {  char* search = (char*)getenv("PATH");
  36.  
  37.      if(search == 0)
  38.        search = ".:~/bin:/usr/mega/bin:/usr/local/bin:/usr/new:/usr/ucb:/usr/bin:/bin:/usr/hosts:/usr/games";
  39.  
  40.      { register char* ptr = search;
  41.        
  42.        while(*ptr)
  43.      { char  name[MAXPATHLEN];
  44.        register char* next = name;
  45.         
  46.        /* copy directory name into [name] */
  47.        while(*ptr && *ptr != ':') *next++ = *ptr++;
  48.        if(*ptr) ptr++;
  49.        
  50.        *next++ = '/'; /* separates directory name and filename */
  51.        
  52.        /* copy filename into [name] */
  53.        { register char* ptr2 = file;
  54.          while(*ptr2) *next++ = *ptr2++;
  55.        }
  56.        
  57.        *next = '\0';
  58.        
  59.        { char* afile = (char*)(name);
  60.          if(exists(afile)) return (afile);
  61.          free(afile);
  62.        }
  63.        
  64.      }
  65.        
  66.      }
  67.      return file;
  68.    }
  69. }
  70.  
  71. #undef binwhich
  72. #ifdef binwhich
  73. main(argc, argv)
  74.   char** argv;
  75. {
  76.  
  77.   argc--; argv++;
  78.  
  79.   while (argc)
  80.     { char* path = which(*argv);
  81.       if(path)
  82.     {
  83.       printf("%s\n", path);
  84.       free(path);
  85.     }
  86.       else
  87.     { char* ptr = search;
  88.       printf("no %s in ", *argv);
  89.       while(*ptr)
  90.         { putchar(*ptr==':' ? ' ' : *ptr);
  91.           ptr++;
  92.         }
  93.       putchar('\n');
  94.     }
  95.       argc--; argv++; 
  96.     }
  97.   exit(0);
  98. }
  99. #endif binwhich
  100.