home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / f / find12as.zip / GLOB.C < prev    next >
C/C++ Source or Header  |  1990-06-14  |  14KB  |  574 lines

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