Advertisement
danielhilst

expandpath.c

Sep 24th, 2014
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/stat.h>
  6.  
  7. #define EXPANDPATH_MAX 256
  8. char *expandpath(const char *cmd)
  9. {
  10.         struct stat st;
  11.         char *pathele, *clpt;   /* path element, colon pointer */
  12.         static char apath[EXPANDPATH_MAX];
  13.  
  14.         pathele = getenv("PATH");
  15.         assert(pathele);
  16.         for (clpt = strchr(pathele, ':'); clpt; pathele = clpt + 1, clpt = strchr(pathele, ':')) {
  17.                 snprintf(apath, EXPANDPATH_MAX, "%.*s/%s", (int)(clpt - pathele), pathele, cmd);
  18.                 if (!stat(apath, &st))
  19.                         return apath;
  20.         }
  21.         snprintf(apath, EXPANDPATH_MAX, "%s/%s", pathele, cmd);
  22.         if (!stat(apath, &st))
  23.             return apath;
  24.        
  25.         return NULL;
  26. }
  27.  
  28. int main(int argc, char **argv)
  29. {
  30.         char *ptr;
  31.  
  32.         assert(argv[1]);
  33.         ptr = expandpath(argv[1]);
  34.         printf("%s\n", (ptr ? ptr : "Not found"));
  35.         return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement