Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  2. #include <libc/stubs.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <ctype.h>
  7. #include <limits.h>
  8. #include <dir.h>
  9.  
  10. /* Search PATH for FILE.
  11.    If successful, store the full pathname in static buffer and return a
  12.    pointer to it.
  13.    If not sucessful, return NULL.
  14.    This is what the Borland searchpath() library function does.
  15. */
  16.  
  17. char *
  18. searchpath(const char *file)
  19. {
  20.   static char found[PATH_MAX];
  21.   static char *path;
  22.  
  23.   memset(found, 0, sizeof(found));
  24.  
  25.   /* Get the PATH and store it for reuse.  */
  26.   if (path == 0)
  27.   {
  28.     char *p = getenv("PATH");
  29.  
  30.     path = (char *)calloc(p ? strlen(p) + 3 : 2, sizeof(char));
  31.     if (path == (char *)0)
  32.       return (char *)0;
  33.  
  34.     /* Prepend `.' to the PATH, so current directory
  35.        is always searched.  */
  36.     path[0] = '.';
  37.  
  38.     if (p)
  39.     {
  40.       register char *s;
  41.  
  42.       path[1] = ';';
  43.       strcpy(path+2, p);
  44.  
  45.       /* Convert to more plausible form.  */
  46.       for (s = path; *s; ++s)
  47.       {
  48.         if (*s == '\\')
  49.           *s = '/';
  50.         if (isupper(*s))
  51.           *s = tolower(*s);
  52.       }
  53.     }
  54.     else
  55.       path[1] = 0;
  56.   }
  57.   if (strpbrk (file, "/\\:") != 0)
  58.   {
  59.     strcpy(found, file);
  60.     return found;
  61.   }
  62.   else
  63.   {
  64.     char *test_dir = path;
  65.  
  66.     do {
  67.       char *dp;
  68.  
  69.       dp = strchr(test_dir, ';');
  70.       if (dp == (char *)0)
  71.         dp = test_dir + strlen(test_dir);
  72.  
  73.       if (dp == test_dir)
  74.         strcpy(found, file);
  75.       else
  76.       {
  77.         strncpy(found, test_dir, dp - test_dir);
  78.         found[dp - test_dir] = '/';
  79.         strcpy(found + (dp - test_dir) + 1, file);
  80.       }
  81.  
  82.       if (__file_exists(found))
  83.         return found;
  84.  
  85.       if (*dp == 0)
  86.         break;
  87.       test_dir = dp + 1;
  88.     } while (*test_dir != 0);
  89.   }
  90.  
  91.   return NULL;
  92. }
  93.