home *** CD-ROM | disk | FTP | other *** search
/ ProfitPress Mega CDROM2 …eeware (MSDOS)(1992)(Eng) / ProfitPress-MegaCDROM2.B6I / MISC / GNU / SED106AS.ZIP / GLOB.C next >
Encoding:
C/C++ Source or Header  |  1989-06-10  |  13.6 KB  |  581 lines

  1. /* File-name wildcard pattern matching for GNU.
  2.    Copyright (C) 1985, 1988, 1989 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* To whomever it may concern: I have never seen the code which most
  19.  Unix programs use to perform this function.  I wrote this from scratch
  20.  based on specifications for the pattern matching.  */
  21.  
  22. #include <sys/types.h>
  23.  
  24. #ifdef    USGr3
  25. #include <dirent.h>
  26. #define direct dirent
  27. #define    D_NAMLEN(d) strlen((d)->d_name)
  28. #else    /* not USGr3    */
  29. #define D_NAMLEN(d) ((d)->d_namlen)
  30. #    ifdef    USG
  31. #include "ndir.h"   /* Get ndir.h from the Emacs distribution.  */
  32. #    else    /* not USG    */
  33. #include <sys/dir.h>
  34. #    endif    /* USG        */
  35. #endif    /* USGr3    */
  36.  
  37. #ifdef USG
  38. #include <memory.h>
  39. #include <string.h>
  40. #define bcopy(s, d, n) ((void) memcpy ((d), (s), (n)))
  41. #define rindex strrchr
  42. struct passwd *getpwent(), *getpwuid(), *getpwnam();
  43.  
  44. extern char *memcpy ();
  45. #else /* not USG */
  46. #include <strings.h>
  47.  
  48. extern void bcopy ();
  49. #endif /* not USG */
  50.  
  51. #ifdef    __GNUC__
  52. #define    alloca(n)    __builtin_alloca (n)
  53. #else    /* Not GCC.  */
  54. #ifdef    sparc
  55. #include <alloca.h>
  56. #else    /* Not sparc.  */
  57. extern char *alloca ();
  58. #endif    /* sparc.  */
  59. #endif    /* GCC.  */
  60.  
  61. #include <pwd.h>
  62.  
  63. extern char *malloc (), *realloc ();
  64. extern void free ();
  65.  
  66. #ifndef NULL
  67. #define NULL 0
  68. #endif
  69.  
  70. /* Zero if * matches .*.  */
  71. int noglob_dot_filenames = 1;
  72.  
  73. /* Nonzero if ~ and ~USER are expanded by glob_filename.  */
  74. int glob_tilde = 0;
  75.  
  76.  
  77. static int glob_match_after_star ();
  78.  
  79. /* Return nonzero if PATTERN has any special globbing chars in it.  */
  80. int
  81. glob_pattern_p (pattern)
  82.      char *pattern;
  83. {
  84.   register char *p = pattern;
  85.   register char c;
  86.  
  87.   while ((c = *p++))
  88.     {
  89.       switch (c)
  90.     {
  91.     case '?':
  92.     case '[':
  93.     case '*':
  94.       return 1;
  95.  
  96.     case '\\':
  97.       if (*p++ == 0) return 0;
  98.     default:
  99.       ;
  100.     }
  101.     }
  102.  
  103.   return 0;
  104. }
  105.  
  106.  
  107. /* Match the pattern PATTERN against the string TEXT;
  108.    return 1 if it matches, 0 otherwise.
  109.  
  110.    A match means the entire string TEXT is used up in matching.
  111.  
  112.    In the pattern string, `*' matches any sequence of characters,
  113.    `?' matches any character, [SET] matches any character in the specified set,
  114.    [^SET] matches any character not in the specified set.
  115.  
  116.    A set is composed of characters or ranges; a range looks like
  117.    character hyphen character (as in 0-9 or A-Z).
  118.    [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
  119.    Any other character in the pattern must be matched exactly.
  120.  
  121.    To suppress the special syntactic significance of any of `[]*?^-\',
  122.    and match the character exactly, precede it with a `\'.
  123.  
  124.    If DOT_SPECIAL is nonzero,
  125.    `*' and `?' do not match `.' at the beginning of TEXT.  */
  126.  
  127. int
  128. glob_match (pattern, text, dot_special)
  129.      char *pattern, *text;
  130.      int dot_special;
  131. {
  132.   register char *p = pattern, *t = text;
  133.   register char c;
  134.  
  135.   while ((c = *p++))
  136.     {
  137.       switch (c)
  138.     {
  139.     case '?':
  140.       if (*t == 0 || (dot_special && t == text && *t == '.')) return 0;
  141.       else ++t;
  142.       break;
  143.  
  144.     case '\\':
  145.       if (*p++ != *t++) return 0;
  146.       break;
  147.  
  148.     case '*':
  149.       if (dot_special && t == text && *t == '.')
  150.         return 0;
  151.       return glob_match_after_star (p, t);
  152.  
  153.     case '[':
  154.       {
  155.         register char c1 = *t++;
  156.         register int invert = (*p == '^');
  157.  
  158.         if (invert) p++;
  159.  
  160.         c = *p++;
  161.         while (1)
  162.           {
  163.         register char cstart = c, cend = c;
  164.  
  165.         if (c == '\\')
  166.           {
  167.             cstart = *p++; cend = cstart;
  168.           }
  169.  
  170.         if (!c) return (0);
  171.  
  172.         c = *p++;
  173.  
  174.         if (c == '-')
  175.           {
  176.             cend = *p++;
  177.             if (cend == '\\')
  178.               cend = *p++;
  179.             if (!cend) return (0);
  180.             c = *p++;
  181.           }
  182.         if (c1 >= cstart && c1 <= cend) goto match;
  183.         if (c == ']')
  184.           break;
  185.           }
  186.         if (!invert) return 0;
  187.         break;
  188.  
  189.       match:
  190.         /* Skip the rest of the [...] construct that already matched.  */
  191.         while (c != ']')
  192.           { 
  193.             if (!c || !(c = *p++)) return (0);
  194.         if (c == '\\') p++;
  195.           }
  196.         if (invert) return 0;
  197.         break;
  198.       }
  199.  
  200.     default:
  201.       if (c != *t++) return 0;
  202.     }
  203.     }
  204.  
  205.   if (*t) return 0;
  206.   return 1;
  207. }
  208.  
  209. /* Like glob_match, but match PATTERN against any final segment of TEXT.  */
  210.  
  211. static int
  212. glob_match_after_star (pattern, text)
  213.      char *pattern, *text;
  214. {
  215.   register char *p = pattern, *t = text;
  216.   register char c, c1;
  217.  
  218.   while ((c = *p++) == '?' || c == '*')
  219.     {
  220.       if (c == '?' && *t++ == 0)
  221.     return 0;
  222.     }
  223.  
  224.   if (c == 0)
  225.     return 1;
  226.  
  227.   if (c == '\\') c1 = *p;
  228.   else c1 = c;
  229.  
  230.   for (;;)
  231.     {
  232.       if ((c == '[' || *t == c1) 
  233.           && glob_match (p - 1, t, 0))
  234.     return 1;
  235.       if (*t++ == 0) return 0;
  236.     }
  237. }
  238.  
  239. /* Return a vector of names of files in directory DIR
  240.    whose names match glob pattern PAT.
  241.    The names are not in any particular order.
  242.    Wildcards at the beginning of PAT do not match an initial period.
  243.  
  244.    The vector is terminated by an element that is a null pointer.
  245.  
  246.    To free the space allocated, first free the vector's elements,
  247.    then free the vector.
  248.  
  249.    Return 0 if cannot get enough memory to hold the pointer
  250.    and the names.
  251.  
  252.    Return -1 if cannot access directory DIR.
  253.    Look in errno for more information.  */
  254.  
  255. char **
  256. glob_vector (pat, dir)
  257.      char *pat;
  258.      char *dir;
  259. {
  260.   struct globval
  261.     {
  262.       struct globval *next;
  263.       char *name;
  264.     };
  265.  
  266.   DIR *d;
  267.   register struct direct *dp;
  268.   struct globval *lastlink;
  269.   register struct globval *nextlink;
  270.   register char *nextname;
  271.   int count;
  272.   int lose;
  273.   register char **name_vector;
  274.   register int i;
  275.  
  276.   if (!(d = opendir (dir)))
  277.     return (char **) -1;
  278.  
  279.   lastlink = 0;
  280.   count = 0;
  281.   lose = 0;
  282.  
  283.   /* Scan the directory, finding all names that match.
  284.      For each name that matches, allocate a struct globval
  285.      on the stack and store the name in it.
  286.      Chain those structs together; lastlink is the front of the chain.  */
  287.   /* Loop reading blocks */
  288.   while (1)
  289.     {
  290.       dp = readdir (d);
  291.       if (!dp) break;
  292.       if (dp->d_ino && glob_match (pat, dp->d_name, noglob_dot_filenames))
  293.     {
  294.       nextlink = (struct globval *) alloca (sizeof (struct globval));
  295.       nextlink->next = lastlink;
  296.       nextname = (char *) malloc (D_NAMLEN(dp) + 1);
  297.       if (!nextname)
  298.         {
  299.           lose = 1;
  300.           break;
  301.         }
  302.       lastlink = nextlink;
  303.       nextlink->name = nextname;
  304.       bcopy (dp->d_name, nextname, D_NAMLEN(dp) + 1);
  305.       count++;
  306.     }
  307.     }
  308.   closedir (d);
  309.  
  310.   name_vector = (char **) malloc ((count + 1) * sizeof (char *));
  311.  
  312.   /* Have we run out of memory?  */
  313.   if (!name_vector || lose)
  314.     {
  315.       /* Here free the strings we have got */
  316.       while (lastlink)
  317.     {
  318.       free (lastlink->name);
  319.       lastlink = lastlink->next;
  320.     }
  321.       return 0;
  322.     }
  323.  
  324.   /* Copy the name pointers from the linked list into the vector */
  325.   for (i = 0; i < count; i++)
  326.     {
  327.       name_vector[i] = lastlink->name;
  328.       lastlink = lastlink->next;
  329.     }
  330.  
  331.   name_vector[count] = 0;
  332.   return name_vector;
  333. }
  334.  
  335. /* Return a new array which is the concatenation of each string in
  336.    ARRAY to DIR. */
  337.  
  338. static char **
  339. glob_dir_to_array (dir, array)
  340.      char *dir, **array;
  341. {
  342.   register int i, l;
  343.   int add_slash = 0;
  344.   char **result;
  345.  
  346.   l = strlen (dir);
  347.   if (!l) return (array);
  348.  
  349.   if (dir[l - 1] != '/') add_slash++;
  350.  
  351.   for (i = 0; array[i]; i++);
  352.  
  353.   result = (char **)malloc ((1 + i) * sizeof (char *));
  354.   if (!result) return (result);
  355.  
  356.   for (i = 0; array[i]; i++) {
  357.     result[i] = (char *)malloc (1 + l + add_slash + strlen (array[i]));
  358.     if (!result[i]) return (char **)NULL;
  359.     strcpy (result[i], dir);
  360.     if (add_slash) strcat (result[i], "/");
  361.     strcat (result[i], array[i]);
  362.   }
  363.   result[i] = (char *)NULL;
  364.  
  365.   /* Free the input array. */
  366.   for (i = 0; array[i]; i++) free (array[i]);
  367.   free (array);
  368.   return (result);
  369. }
  370.  
  371. /* Do globbing on PATHNAME.  Return an array of pathnames that match,
  372.    marking the end of the array with a null-pointer as an element.
  373.    If no pathnames match, then the array is empty (first element is null).
  374.    If there isn't enough memory, then return NULL.
  375.    If a file system error occurs, return -1; `errno' has the error code.
  376.  
  377.    Wildcards at the beginning of PAT, or following a slash,
  378.    do not match an initial period.  */
  379.  
  380. char **
  381. glob_filename (pathname)
  382.      char *pathname;
  383. {
  384.   char **result;
  385.   unsigned int result_size;
  386.   char *directory_name, *filename;
  387.   unsigned int directory_len;
  388.  
  389.   result = (char **) malloc (sizeof (char *));
  390.   result_size = 1;
  391.   if (result == NULL)
  392.     return NULL;
  393.  
  394.   result[0] = NULL;
  395.  
  396.   /* Find the filename.  */
  397.   filename = rindex (pathname, '/');
  398.   if (filename == 0)
  399.     {
  400.       filename = pathname;
  401.       directory_name = "";
  402.       directory_len = 0;
  403.     }
  404.   else
  405.     {
  406.       directory_len = filename - pathname;
  407.       directory_name = (char *) alloca (directory_len + 1);
  408.       bcopy (pathname, directory_name, directory_len);
  409.       directory_name[directory_len] = '\0';
  410.       ++filename;
  411.     }
  412.  
  413.   if (glob_tilde && *pathname == '~')
  414.     {
  415.       if (directory_len == 0)
  416.     {
  417.       filename = directory_name;
  418.       directory_name = pathname;
  419.       directory_len = strlen (directory_name);
  420.     }
  421.  
  422.       if (directory_len == 1)
  423.     {
  424.       extern char *getenv ();
  425.       static char *home_directory = 0;
  426.       static unsigned int home_len;
  427.  
  428.       if (home_directory == 0)
  429.         {
  430.           home_directory = getenv ("HOME");
  431.           if (home_directory == NULL)
  432.         {
  433.           home_directory == "";
  434.           home_len = 0;
  435.         }
  436.           else
  437.         home_len = strlen (home_directory);
  438.         }
  439.  
  440.       directory_name = home_directory;
  441.       directory_len = home_len;
  442.     }
  443.       else
  444.     {
  445.       struct passwd *pwent = getpwnam (directory_name + 1);
  446.       if (pwent == 0)
  447.         {
  448.           directory_name = "";
  449.           directory_len = 0;
  450.         }
  451.       else
  452.         {
  453.           directory_name = pwent->pw_dir;
  454.           directory_len = strlen (directory_name);
  455.         }
  456.     }
  457.     }
  458.   else if (glob_pattern_p (directory_name))
  459.     {
  460.       /* If directory_name contains globbing characters, then we
  461.      have to expand the previous levels.  Just recurse. */
  462.       char **directories;
  463.       register unsigned int i;
  464.  
  465.       if (directory_name[directory_len - 1] == '/')
  466.     directory_name[directory_len - 1] = '\0';
  467.  
  468.       directories = glob_filename (directory_name);
  469.       if (directories == NULL)
  470.     goto memory_error;
  471.       else if ((int) directories == -1)
  472.     return (char **) -1;
  473.       else if (*directories == NULL)
  474.     {
  475.       free ((char *) directories);
  476.       return (char **) -1;
  477.     }
  478.  
  479.       /* We have successfully globbed the preceding directory name.
  480.      For each name in DIRECTORIES, call glob_vector on it and
  481.      FILENAME.  Concatenate the results together.  */
  482.       for (i = 0; directories[i] != NULL; ++i)
  483.     {
  484.       char **temp_results = glob_vector (filename, directories[i]);
  485.       if (temp_results == NULL)
  486.         goto memory_error;
  487.       else if ((int) temp_results == -1)
  488.         /* This filename is probably not a directory.  Ignore it.  */
  489.         ;
  490.       else
  491.         {
  492.           char **array = glob_dir_to_array (directories[i], temp_results);
  493.  
  494.           register unsigned int l = 0;
  495.           while (array[l] != NULL)
  496.         ++l;
  497.  
  498.           result = (char **) realloc (result,
  499.                       (result_size + 1) * sizeof (char *));
  500.           if (result == NULL)
  501.         goto memory_error;
  502.  
  503.           for (l = 0; array[l] != NULL; ++l)
  504.         result[result_size++ - 1] = array[l];
  505.           result[result_size - 1] = NULL;
  506.           free ((char *) array);
  507.         }
  508.     }
  509.       /* Free the directories.  */
  510.       for (i = 0; directories[i]; i++)
  511.     free (directories[i]);
  512.       free ((char *) directories);
  513.  
  514.       return result;
  515.     }
  516.  
  517.   if (*filename == '\0')
  518.     {
  519.       /* If there is only a directory name, return it.  */
  520.       result = (char **) realloc ((char *) result, 2 * sizeof (char *));
  521.       if (result == NULL)
  522.     return NULL;
  523.       result[0] = (char *) malloc (directory_len + 1);
  524.       if (result[0] == NULL)
  525.     goto memory_error;
  526.       bcopy (directory_name, result[0], directory_len + 1);
  527.       result[1] = NULL;
  528.       return result;
  529.     }
  530.   else
  531.     {
  532.       /* Otherwise, just return what glob_vector
  533.      returns appended to the directory name. */
  534.       char **temp_results = glob_vector (filename,
  535.                      (directory_len == 0
  536.                       ? "." : directory_name));
  537.  
  538.       if (temp_results == NULL || (int) temp_results == -1)
  539.     return temp_results;
  540.  
  541.       return glob_dir_to_array (directory_name, temp_results);
  542.     }
  543.  
  544.   memory_error:;
  545.   if (result != NULL)
  546.     {
  547.       register unsigned int i;
  548.       for (i = 0; result[i] != NULL; ++i)
  549.     free (result[i]);
  550.       free ((char *) result);
  551.     }
  552.   return NULL;
  553. }
  554.  
  555.  
  556.  
  557. #ifdef TEST
  558.  
  559. main (argc, argv)
  560.      int argc;
  561.      char **argv;
  562. {
  563.   char **value;
  564.   int i, index = 1;
  565.  
  566.   while (index < argc) {
  567.     value = glob_filename (argv[index]);
  568.     if ((int) value == 0)
  569.       printf ("Memory exhausted.\n");
  570.     else if ((int) value == -1)
  571.       perror (argv[index]);
  572.     else
  573.       for (i = 0; value[i]; i++)
  574.     printf ("%s\n", value[i]);
  575.     index++;
  576.   }
  577.   return 0;
  578. }
  579.  
  580. #endif /* TEST */
  581.