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