   This file documents the GNU C library.

   This is Edition 0.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 Free Software
Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

User influence on `gettext'
...........................

   The last sections described what the programmer can do to
internationalize the messages of the program.  But it is finally up to
the user to select the message s/he wants to see.  S/He must understand
them.

   The POSIX locale model uses the environment variables `LC_COLLATE',
`LC_CTYPE', `LC_MESSAGES', `LC_MONETARY', `NUMERIC', and `LC_TIME' to
select the locale which is to be used.  This way the user can influence
lots of functions.  As we mentioned above the `gettext' functions also
take advantage of this.

   To understand how this happens it is necessary to take a look at the
various components of the filename which gets computed to locate a
message catalog.  It is composed as follows:

     DIR_NAME/LOCALE/LC_CATEGORY/DOMAIN_NAME.mo

   The default value for DIR_NAME is system specific.  It is computed
from the value given as the prefix while configuring the C library.
This value normally is `/usr' or `/'.  For the former the complete
DIR_NAME is:

     /usr/share/locale

   We can use `/usr/share' since the `.mo' files containing the message
catalogs are system independent, all systems can use the same files.
If the program executed the `bindtextdomain' function for the message
domain that is currently handled the `dir_name' component is the
exactly the value which was given to the function as the second
parameter.  I.e., `bindtextdomain' allows to overwrite the only system
dependent and fixed value to make it possible to address file
everywhere in the filesystem.

   The CATEGORY is the name of the locale category which was selected
in the program code.  For `gettext' and `dgettext' this is always
`LC_MESSAGES', for `dcgettext' this is selected by the value of the
third parameter.  As said above it should be avoided to ever use a
category other than `LC_MESSAGES'.

   The LOCALE component is computed based on the category used.  Just
like for the `setlocale' function here comes the user selection into
the play.  Some environment variables are examined in a fixed order and
the first environment variable set determines the return value of the
lookup process.  In detail, for the category `LC_xxx' the following
variables in this order are examined:

`LANGUAGE'

`LC_ALL'

`LC_xxx'

`LANG'
   This looks very familiar.  With the exception of the `LANGUAGE'
environment variable this is exactly the lookup order the `setlocale'
function uses.  But why introducing the `LANGUAGE' variable?

   The reason is that the syntax of the values these variables can have
is different to what is expected by the `setlocale' function.  If we
would set `LC_ALL' to a value following the extended syntax that would
mean the `setlocale' function will never be able to use the value of
this variable as well.  An additional variable removes this problem
plus we can select the language independently of the locale setting
which sometimes is useful.

   While for the `LC_xxx' variables the value should consist of exactly
one specification of a locale the `LANGUAGE' variable's value can
consist of a colon separated list of locale names.  The attentive
reader will realize that this is the way we manage to implement one of
our additional demands above: we want to be able to specify an ordered
list of language.

   Back to the constructed filename we have only one component missing.
The DOMAIN_NAME part is the name which was either registered using the
`textdomain' function or which was given to `dgettext' or `dcgettext'
as the first parameter.  Now it becomes obvious that a good choice for
the domain name in the program code is a string which is closely
related to the program/package name.  E.g., for the GNU C Library the
domain name is `libc'.

A limit piece of example code should show how the programmer is supposed
to work:

     {
       textdomain ("test-package");
       bindtextdomain ("test-package", "/usr/local/share/locale");
       puts (gettext ("Hello, world!");
     }

   At the program start the default domain is `messages'.  The
`textdomain' call changes this to `test-package'.  The `bindtextdomain'
call specifies that the message catalogs for the domain `test-package'
can be found below the directory `/usr/local/share/locale'.

   If now the user set in her/his environment the variable `LANGUAGE'
to `de' the `gettext' function will try to use the translations from
the file

     /usr/local/share/locale/de/LC_MESSAGES/test-package.mo

   From the above descriptions it should be clear which component of
this filename is determined by which source.

   In the above example we assumed that the `LANGUAGE' environment
variable to `de'.  This might be an appropriate selection but what
happens if the user wants to use `LC_ALL' because of the wider
usability and here the required value is `de_DE.ISO-8859-1'?  We
already mentioned above that a situation like this is not infrequent.
E.g., a person might prefer reading a dialect and if this is not
available fall back on the standard language.

   The `gettext' functions know about situations like this and can
handle them gracefully.  The functions recognize the format of the value
of the environment variable.  It can split the value is different pieces
and by leaving out the only or the other part it can construct new
values.  This happens of course in a predictable way.  To understand
this one must know the format of the environment variable value.  There
are to more or less standardized forms:

_X/Open Format_
     `language[_territory[.codeset]][@modifier]'

_CEN Format (European Community Standard)_
     `language[_territory][+audience][+special][,[sponsor][_revision]]'

   The functions will automatically recognize which format is used.
Less specific locale names will be stripped of in the order of the
following list:

  1. `revision'

  2. `sponsor'

  3. `special'

  4. `codeset'

  5. `normalized codeset'

  6. `territory'

  7. `audience'/`modifier'

   From the last entry one can see that the meaning of the `modifier'
field in the X/Open format and the `audience' format have the same
meaning.  Beside one can see that the `language' field for obvious
reasons never will be dropped.

   The only new thing is the `normalized codeset' entry.  This is
another goodie which is introduced to help reducing the chaos which
derives from the inability of the people to standardize the names of
character sets.  Instead of ISO-8859-1 one can often see 8859-1, 88591,
iso8859-1, or iso_8859-1.  The `normalized codeset' value is generated
from the user-provided character set name by applying the following
rules:

  1. Remove all characters beside numbers and letters.

  2. Fold letters to lowercase.

  3. If the same only contains digits prepend the string `"iso"'.

So all of the above name will be normalized to `iso88591'.  This allows
the program user much more freely choosing the locale name.

   Even this extended functionality still does not help to solve the
problem that completely different names can be used to denote the same
locale (e.g., `de' and `german').  To be of help in this situation the
locale implementation and also the `gettext' functions know about
aliases.

   The file `/usr/share/locale/locale.alias' (replace `/usr' with
whatever prefix you used for configuring the C library) contains a
mapping of alternative names to more regular names.  The system manager
is free to add new entries to fill her/his own needs.  The selected
locale from the environment is compared with the entries in the first
column of this file ignoring the case.  If they match the value of the
second column is used instead for the further handling.

   In the description of the format of the environment variables we
already mentioned the character set as a factor in the selection of the
message catalog.  In fact, only catalogs which contain text written
using the character set of the system/program can be used (directly;
there will come a solution for this some day).  This means for the user
that s/he will always have to take care for this.  If in the collection
of the message catalogs there are files for the same language but coded
using different character sets the user has to be careful.

Programs to handle message catalogs for `gettext'
-------------------------------------------------

   The GNU C Library does not contain the source code for the programs
to handle message catalogs for the `gettext' functions.  As part of the
GNU project the GNU gettext package contains everything the developer
needs.  The functionality provided by the tools in this package by far
exceeds the abilities of the `gencat' program described above for the
`catgets' functions.

   There is a program `msgfmt' which is the equivalent program to the
`gencat' program.  It generates from the human-readable and -editable
form of the message catalog a binary file which can be used by the
`gettext' functions.  But there are several more programs available.

   The `xgettext' program can be used to automatically extract the
translatable messages from a source file.  I.e., the programmer need not
take care for the translations and the list of messages which have to be
translated.  S/He will simply wrap the translatable string in calls to
`gettext' et.al and the rest will be done by `xgettext'.  This program
has a lot of option which help to customize the output or do help to
understand the input better.

   Other programs help to the manage development cycle when new
messages appear in the source files or when a new translation of the
messages appear.  Here it should only be noted that using all the tools
in GNU gettext it is possible to _completely_ automate the handling of
message catalogs.  Beside marking the translatable string in the source
code and generating the translations the developers do not have to do
anything themselves.

Searching and Sorting
*********************

   This chapter describes functions for searching and sorting arrays of
arbitrary objects.  You pass the appropriate comparison function to be
applied as an argument, along with the size of the objects in the array
and the total number of elements.

Defining the Comparison Function
================================

   In order to use the sorted array library functions, you have to
describe how to compare the elements of the array.

   To do this, you supply a comparison function to compare two elements
of the array.  The library will call this function, passing as arguments
pointers to two array elements to be compared.  Your comparison function
should return a value the way `strcmp' (see String/Array Comparison)
does: negative if the first argument is "less" than the
second, zero if they are "equal", and positive if the first argument is
"greater".

   Here is an example of a comparison function which works with an
array of numbers of type `double':

     int
     compare_doubles (const void *a, const void *b)
     {
       const double *da = (const double *) a;
       const double *db = (const double *) b;

       return (*da > *db) - (*da < *db);
     }

   The header file `stdlib.h' defines a name for the data type of
comparison functions.  This type is a GNU extension.

     int comparison_fn_t (const void *, const void *);

Array Search Function
=====================

   Generally searching for a specific element in an array means that
potentially all elements must be checked.  The GNU C library contains
functions to perform linear search.  The prototypes for the following
two functions can be found in `search.h'.

 - Function: void * lfind (const void *KEY, void *BASE, size_t *NMEMB,
          size_t SIZE, comparison_fn_t COMPAR)
     The `lfind' function searches in the array with `*NMEMB' elements
     of SIZE bytes pointed to by BASE for an element which matches the
     one pointed to by KEY.  The function pointed to by COMPAR is used
     decide whether two elements match.

     The return value is a pointer to the matching element in the array
     starting at BASE if it is found.  If no matching element is
     available `NULL' is returned.

     The mean runtime of this function is `*NMEMB'/2.  This function
     should only be used elements often get added to or deleted from
     the array in which case it might not be useful to sort the array
     before searching.

 - Function: void * lsearch (const void *KEY, void *BASE, size_t
          *NMEMB, size_t SIZE, comparison_fn_t COMPAR)
     The `lsearch' function is similar to the `lfind' function.  It
     searches the given array for an element and returns it if found.
     The difference is that if no matching element is found the
     `lsearch' function adds the object pointed to by KEY (with a size
     of SIZE bytes) at the end of the array and it increments the value
     of `*NMEMB' to reflect this addition.

     This means for the caller that if it is not sure that the array
     contains the element one is searching for the memory allocated for
     the array starting at BASE must have room for at least SIZE more
     bytes.  If one is sure the element is in the array it is better to
     use `lfind' so having more room in the array is always necessary
     when calling `lsearch'.

   To search a sorted array for an element matching the key, use the
`bsearch' function.  The prototype for this function is in the header
file `stdlib.h'.

 - Function: void * bsearch (const void *KEY, const void *ARRAY, size_t
          COUNT, size_t SIZE, comparison_fn_t COMPARE)
     The `bsearch' function searches the sorted array ARRAY for an
     object that is equivalent to KEY.  The array contains COUNT
     elements, each of which is of size SIZE bytes.

     The COMPARE function is used to perform the comparison.  This
     function is called with two pointer arguments and should return an
     integer less than, equal to, or greater than zero corresponding to
     whether its first argument is considered less than, equal to, or
     greater than its second argument.  The elements of the ARRAY must
     already be sorted in ascending order according to this comparison
     function.

     The return value is a pointer to the matching array element, or a
     null pointer if no match is found.  If the array contains more
     than one element that matches, the one that is returned is
     unspecified.

     This function derives its name from the fact that it is implemented
     using the binary search algorithm.

Array Sort Function
===================

   To sort an array using an arbitrary comparison function, use the
`qsort' function.  The prototype for this function is in `stdlib.h'.

 - Function: void qsort (void *ARRAY, size_t COUNT, size_t SIZE,
          comparison_fn_t COMPARE)
     The QSORT function sorts the array ARRAY.  The array contains
     COUNT elements, each of which is of size SIZE.

     The COMPARE function is used to perform the comparison on the
     array elements.  This function is called with two pointer
     arguments and should return an integer less than, equal to, or
     greater than zero corresponding to whether its first argument is
     considered less than, equal to, or greater than its second
     argument.

     *Warning:* If two objects compare as equal, their order after
     sorting is unpredictable.  That is to say, the sorting is not
     stable.  This can make a difference when the comparison considers
     only part of the elements.  Two elements with the same sort key
     may differ in other respects.

     If you want the effect of a stable sort, you can get this result by
     writing the comparison function so that, lacking other reason
     distinguish between two elements, it compares them by their
     addresses.  Note that doing this may make the sorting algorithm
     less efficient, so do it only if necessary.

     Here is a simple example of sorting an array of doubles in
     numerical order, using the comparison function defined above
     (see Comparison Functions):

          {
            double *array;
            int size;
            ...
            qsort (array, size, sizeof (double), compare_doubles);
          }

     The `qsort' function derives its name from the fact that it was
     originally implemented using the "quick sort" algorithm.

Searching and Sorting Example
=============================

   Here is an example showing the use of `qsort' and `bsearch' with an
array of structures.  The objects in the array are sorted by comparing
their `name' fields with the `strcmp' function.  Then, we can look up
individual objects based on their names.

     #include <stdlib.h>
     #include <stdio.h>
     #include <string.h>

     /* Define an array of critters to sort. */

     struct critter
       {
         const char *name;
         const char *species;
       };

     struct critter muppets[] =
       {
         {"Kermit", "frog"},
         {"Piggy", "pig"},
         {"Gonzo", "whatever"},
         {"Fozzie", "bear"},
         {"Sam", "eagle"},
         {"Robin", "frog"},
         {"Animal", "animal"},
         {"Camilla", "chicken"},
         {"Sweetums", "monster"},
         {"Dr. Strangepork", "pig"},
         {"Link Hogthrob", "pig"},
         {"Zoot", "human"},
         {"Dr. Bunsen Honeydew", "human"},
         {"Beaker", "human"},
         {"Swedish Chef", "human"}
       };

     int count = sizeof (muppets) / sizeof (struct critter);

     /* This is the comparison function used for sorting and searching. */

     int
     critter_cmp (const struct critter *c1, const struct critter *c2)
     {
       return strcmp (c1->name, c2->name);
     }

     /* Print information about a critter. */

     void
     print_critter (const struct critter *c)
     {
       printf ("%s, the %s\n", c->name, c->species);
     }

     /* Do the lookup into the sorted array. */

     void
     find_critter (const char *name)
     {
       struct critter target, *result;
       target.name = name;
       result = bsearch (&target, muppets, count, sizeof (struct critter),
                         critter_cmp);
       if (result)
         print_critter (result);
       else
         printf ("Couldn't find %s.\n", name);
     }

     /* Main program. */

     int
     main (void)
     {
       int i;

       for (i = 0; i < count; i++)
         print_critter (&muppets[i]);
       printf ("\n");

       qsort (muppets, count, sizeof (struct critter), critter_cmp);

       for (i = 0; i < count; i++)
         print_critter (&muppets[i]);
       printf ("\n");

       find_critter ("Kermit");
       find_critter ("Gonzo");
       find_critter ("Janice");

       return 0;
     }

   The output from this program looks like:

     Kermit, the frog
     Piggy, the pig
     Gonzo, the whatever
     Fozzie, the bear
     Sam, the eagle
     Robin, the frog
     Animal, the animal
     Camilla, the chicken
     Sweetums, the monster
     Dr. Strangepork, the pig
     Link Hogthrob, the pig
     Zoot, the human
     Dr. Bunsen Honeydew, the human
     Beaker, the human
     Swedish Chef, the human

     Animal, the animal
     Beaker, the human
     Camilla, the chicken
     Dr. Bunsen Honeydew, the human
     Dr. Strangepork, the pig
     Fozzie, the bear
     Gonzo, the whatever
     Kermit, the frog
     Link Hogthrob, the pig
     Piggy, the pig
     Robin, the frog
     Sam, the eagle
     Swedish Chef, the human
     Sweetums, the monster
     Zoot, the human

     Kermit, the frog
     Gonzo, the whatever
     Couldn't find Janice.

The `hsearch' function.
=======================

   The functions mentioned so far in this chapter are searching in a
sorted or unsorted array.  There are other methods to organize
information which later should be searched.  The costs of insert,
delete and search differ.  One possible implementation is using hashing
tables.

 - Function: int hcreate (size_t NEL)
     The `hcreate' function creates a hashing table which can contain at
     least NEL elements.  There is no possibility to grow this table so
     it is necessary to choose the value for NEL wisely.  The used
     methods to implement this function might make it necessary to make
     the number of elements in the hashing table larger than the
     expected maximal number of elements.  Hashing tables usually work
     inefficient if they are filled 80% or more.  The constant access
     time guaranteed by hashing can only be achieved if few collisions
     exist.  See Knuth's "The Art of Computer Programming, Part 3:
     Searching and Sorting" for more information.

     The weakest aspect of this function is that there can be at most
     one hashing table used through the whole program.  The table is
     allocated in local memory out of control of the programmer.  As an
     extension the GNU C library provides an additional set of
     functions with an reentrant interface which provide a similar
     interface but which allow to keep arbitrarily many hashing tables.

     It is possible to use more than one hashing table in the program
     run if the former table is first destroyed by a call to `hdestroy'.

     The function returns a non-zero value if successful.  If it return
     zero something went wrong.  This could either mean there is
     already a hashing table in use or the program runs out of memory.

 - Function: void hdestroy (void)
     The `hdestroy' function can be used to free all the resources
     allocated in a previous call of `hcreate'.  After a call to this
     function it is again possible to call `hcreate' and allocate a new
     table with possibly different size.

     It is important to remember that the elements contained in the
     hashing table at the time `hdestroy' is called are _not_ freed by
     this function.  It is the responsibility of the program code to
     free those strings (if necessary at all).  Freeing all the element
     memory is not possible without extra, separately kept information
     since there is no function to iterate through all available
     elements in the hashing table.  If it is really necessary to free
     a table and all elements the programmer has to keep a list of all
     table elements and before calling `hdestroy' s/he has to free all
     element's data using this list.  This is a very unpleasant
     mechanism and it also shows that this kind of hashing tables is
     mainly meant for tables which are created once and used until the
     end of the program run.

   Entries of the hashing table and keys for the search are defined
using this type:

 - Data type: struct ENTRY
     Both elements of this structure are pointers to zero-terminated
     strings.  This is a limiting restriction of the functionality of
     the `hsearch' functions.  They can only be used for data sets
     which use the NUL character always and solely to terminate the
     records.  It is not possible to handle general binary data.

    `char *key'
          Pointer to a zero-terminated string of characters describing
          the key for the search or the element in the hashing table.

    `char *data'
          Pointer to a zero-terminated string of characters describing
          the data.  If the functions will be called only for searching
          an existing entry this element might stay undefined since it
          is not used.

 - Function: ENTRY * hsearch (ENTRY ITEM, ACTION ACTION)
     To search in a hashing table created using `hcreate' the `hsearch'
     function must be used.  This function can perform simple search
     for an element (if ACTION has the `FIND') or it can alternatively
     insert the key element into the hashing table, possibly replacing
     a previous value (if ACTION is `ENTER').

     The key is denoted by a pointer to an object of type `ENTRY'.  For
     locating the corresponding position in the hashing table only the
     `key' element of the structure is used.

     The return value depends on the ACTION parameter value.  If it is
     `FIND' the value is a pointer to the matching element in the
     hashing table or `NULL' if no matching element exists.  If ACTION
     is `ENTER' the return value is only `NULL' if the programs runs
     out of memory while adding the new element to the table.
     Otherwise the return value is a pointer to the element in the
     hashing table which contains newly added element based on the data
     in KEY.

   As mentioned before the hashing table used by the functions
described so far is global and there can be at any time at most one
hashing table in the program.  A solution is to use the following
functions which are a GNU extension.  All have in common that they
operate on a hashing table which is described by the content of an
object of the type `struct hsearch_data'.  This type should be treated
as opaque, none of its members should be changed directly.

 - Function: int hcreate_r (size_t NEL, struct hsearch_data *HTAB)
     The `hcreate_r' function initializes the object pointed to by HTAB
     to contain a hashing table with at least NEL elements.  So this
     function is equivalent to the `hcreate' function except that the
     initialized data structure is controlled by the user.

     This allows to have more than once hashing table at one time.  The
     memory necessary for the `struct hsearch_data' object can be
     allocated dynamically.

     The return value is non-zero if the operation were successful.  if
     the return value is zero something went wrong which probably means
     the programs runs out of memory.

 - Function: void hdestroy_r (struct hsearch_data *HTAB)
     The `hdestroy_r' function frees all resources allocated by the
     `hcreate_r' function for this very same object HTAB.  As for
     `hdestroy' it is the programs responsibility to free the strings
     for the elements of the table.

 - Function: int hsearch_r (ENTRY ITEM, ACTION ACTION, ENTRY **RETVAL,
          struct hsearch_data *HTAB)
     The `hsearch_r' function is equivalent to `hsearch'.  The meaning
     of the first two arguments is identical.  But instead of operating
     on a single global hashing table the function works on the table
     described by the object pointed to by HTAB (which is initialized
     by a call to `hcreate_r').

     Another difference to `hcreate' is that the pointer to the found
     entry in the table is not the return value of the functions.  It is
     returned by storing it in a pointer variables pointed to by the
     RETVAL parameter.  The return value of the function is an integer
     value indicating success if it is non-zero and failure if it is
     zero.  In the latter case the global variable ERRNO signals the
     reason for the failure.

    `ENOMEM'
          The table is filled and `hsearch_r' was called with an so far
          unknown key and ACTION set to `ENTER'.

    `ESRCH'
          The ACTION parameter is `FIND' and no corresponding element
          is found in the table.

The `tsearch' function.
=======================

   Another common form to organize data for efficient search is to use
trees.  The `tsearch' function family provides a nice interface to
functions to organize possibly large amounts of data by providing a mean
access time proportional to the logarithm of the number of elements.
The GNU C library implementation even guarantees that this bound is
never exceeded even for input data which cause problems for simple
binary tree implementations.

   The functions described in the chapter are all described in the
System V and X/Open specifications and are therefore quite portable.

   In contrast to the `hsearch' functions the `tsearch' functions can
be used with arbitrary data and not only zero-terminated strings.

   The `tsearch' functions have the advantage that no function to
initialize data structures is necessary.  A simple pointer of type
`void *' initialized to `NULL' is a valid tree and can be extended or
searched.

 - Function: void * tsearch (const void *KEY, void **ROOTP,
          comparison_fn_t COMPAR)
     The `tsearch' function searches in the tree pointed to by `*ROOTP'
     for an element matching KEY.  The function pointed to by COMPAR is
     used to determine whether two elements match.  See Comparison Functions,
     for a specification of the functions which can be
     used for the COMPAR parameter.

     If the tree does not contain a matching entry the KEY value will
     be added to the tree.  `tsearch' does not make a copy of the object
     pointed to by KEY (how could it since the size is unknown).
     Instead it adds a reference to this object which means the object
     must be available as long as the tree data structure is used.

     The tree is represented by a pointer to a pointer since it is
     sometimes necessary to change the root node of the tree.  So it
     must not be assumed that the variable pointed to by ROOTP has the
     same value after the call.  This also shows that it is not safe to
     call the `tsearch' function more than once at the same time using
     the same tree.  It is no problem to run it more than once at a
     time on different trees.

     The return value is a pointer to the matching element in the tree.
     If a new element was created the pointer points to the new data
     (which is in fact KEY).  If an entry had to be created and the
     program ran out of space `NULL' is returned.

 - Function: void * tfind (const void *KEY, void *const *ROOTP,
          comparison_fn_t COMPAR)
     The `tfind' function is similar to the `tsearch' function.  It
     locates an element matching the one pointed to by KEY and returns
     a pointer to this element.  But if no matching element is
     available no new element is entered (note that the ROOTP parameter
     points to a constant pointer).  Instead the function returns
     `NULL'.

   Another advantage of the `tsearch' function in contrast to the
`hsearch' functions is that there is an easy way to remove elements.

 - Function: void * tdelete (const void *KEY, void **ROOTP,
          comparison_fn_t COMPAR)
     To remove a specific element matching KEY from the tree `tdelete'
     can be used.  It locates the matching element using the same
     method as `tfind'.  The corresponding element is then removed and
     the data if this tree node is returned by the function.  If there
     is no matching entry in the tree nothing can be deleted and the
     function returns `NULL'.

 - Function: void tdestroy (void *VROOT, __free_fn_t FREEFCT)
     If the complete search tree has to be removed one can use
     `tdestroy'.  It frees all resources allocated by the `tsearch'
     function to generate the tree pointed to by VROOT.

     For the data in each tree node the function FREEFCT is called.
     The pointer to the data is passed as the argument to the function.
     If no such work is necessary FREEFCT must point to a function
     doing nothing.  It is called in any case.

     This function is a GNU extension and not covered by the System V or
     X/Open specifications.

   In addition to the function to create and destroy the tree data
structure there is another function which allows to apply a function on
all elements of the tree.  The function must have this type:

     void __action_fn_t (const void *nodep, VISIT value, int level);

   The NODEP is the data value of the current node (once given as the
KEY argument to `tsearch').  LEVEL is a numeric value which corresponds
to the depth of the current node in the tree.  The root node has the
depth 0 and its children have a depth of 1 and so on.  The `VISIT' type
is an enumeration type.

 - Data Type: VISIT
     The `VISIT' value indicates the status of the current node in the
     tree and how the function is called.  The status of a node is
     either `leaf' or `internal node'.  For each leaf node the function
     is called exactly once, for each internal node it is called three
     times: before the first child is processed, after the first child
     is processed and after both children are processed.  This makes it
     possible to handle all three methods of tree traversal (or even a
     combination of them).

    `preorder'
          The current node is an internal node and the function is
          called before the first child was processed.

    `endorder'
          The current node is an internal node and the function is
          called after the first child was processed.

    `postorder'
          The current node is an internal node and the function is
          called after the second child was processed.

    `leaf'
          The current node is a leaf.

 - Function: void twalk (const void *ROOT, __action_fn_t ACTION)
     For each node in the tree with a node pointed to by ROOT the
     `twalk' function calls the function provided by the parameter
     ACTION.  For leaf nodes the function is called exactly once with
     VALUE set to `leaf'.  For internal nodes the function is called
     three times, setting the VALUE parameter or ACTION to the
     appropriate value.  The LEVEL argument for the ACTION function is
     computed while descending the tree with increasing the value by
     one for the descend to a child, starting with the value 0 for the
     root node.

     Since the functions used for the ACTION parameter to `twalk' must
     not modify the tree data it is safe to run `twalk' is more than
     one thread at the same time working on the same tree.  It is also
     safe to call `tfind' in parallel.  Functions which modify the tree
     must not be used.  Otherwise the behaviour is undefined.

Pattern Matching
****************

   The GNU C Library provides pattern matching facilities for two kinds
of patterns: regular expressions and file-name wildcards.  The library
also provides a facility for expanding variable and command references
and parsing text into words in the way the shell does.

Wildcard Matching
=================

   This section describes how to match a wildcard pattern against a
particular string.  The result is a yes or no answer: does the string
fit the pattern or not.  The symbols described here are all declared in
`fnmatch.h'.

 - Function: int fnmatch (const char *PATTERN, const char *STRING, int
          FLAGS)
     This function tests whether the string STRING matches the pattern
     PATTERN.  It returns `0' if they do match; otherwise, it returns
     the nonzero value `FNM_NOMATCH'.  The arguments PATTERN and STRING
     are both strings.

     The argument FLAGS is a combination of flag bits that alter the
     details of matching.  See below for a list of the defined flags.

     In the GNU C Library, `fnmatch' cannot experience an "error"--it
     always returns an answer for whether the match succeeds.  However,
     other implementations of `fnmatch' might sometimes report "errors".
     They would do so by returning nonzero values that are not equal to
     `FNM_NOMATCH'.

   These are the available flags for the FLAGS argument:

`FNM_FILE_NAME'
     Treat the `/' character specially, for matching file names.  If
     this flag is set, wildcard constructs in PATTERN cannot match `/'
     in STRING.  Thus, the only way to match `/' is with an explicit
     `/' in PATTERN.

`FNM_PATHNAME'
     This is an alias for `FNM_FILE_NAME'; it comes from POSIX.2.  We
     don't recommend this name because we don't use the term "pathname"
     for file names.

`FNM_PERIOD'
     Treat the `.' character specially if it appears at the beginning of
     STRING.  If this flag is set, wildcard constructs in PATTERN
     cannot match `.' as the first character of STRING.

     If you set both `FNM_PERIOD' and `FNM_FILE_NAME', then the special
     treatment applies to `.' following `/' as well as to `.' at the
     beginning of STRING.  (The shell uses the `FNM_PERIOD' and
     `FNM_FILE_NAME' flags together for matching file names.)

`FNM_NOESCAPE'
     Don't treat the `\' character specially in patterns.  Normally,
     `\' quotes the following character, turning off its special meaning
     (if any) so that it matches only itself.  When quoting is enabled,
     the pattern `\?' matches only the string `?', because the question
     mark in the pattern acts like an ordinary character.

     If you use `FNM_NOESCAPE', then `\' is an ordinary character.

`FNM_LEADING_DIR'
     Ignore a trailing sequence of characters starting with a `/' in
     STRING; that is to say, test whether STRING starts with a
     directory name that PATTERN matches.

     If this flag is set, either `foo*' or `foobar' as a pattern would
     match the string `foobar/frobozz'.

`FNM_CASEFOLD'
     Ignore case in comparing STRING to PATTERN.

Globbing
========

   The archetypal use of wildcards is for matching against the files in
a directory, and making a list of all the matches.  This is called
"globbing".

   You could do this using `fnmatch', by reading the directory entries
one by one and testing each one with `fnmatch'.  But that would be slow
(and complex, since you would have to handle subdirectories by hand).

   The library provides a function `glob' to make this particular use
of wildcards convenient.  `glob' and the other symbols in this section
are declared in `glob.h'.

Calling `glob'
--------------

   The result of globbing is a vector of file names (strings).  To
return this vector, `glob' uses a special data type, `glob_t', which is
a structure.  You pass `glob' the address of the structure, and it
fills in the structure's fields to tell you about the results.

 - Data Type: glob_t
     This data type holds a pointer to a word vector.  More precisely,
     it records both the address of the word vector and its size.  The
     GNU implementation contains some more fields which are non-standard
     extensions.

    `gl_pathc'
          The number of elements in the vector.

    `gl_pathv'
          The address of the vector.  This field has type `char **'.

    `gl_offs'
          The offset of the first real element of the vector, from its
          nominal address in the `gl_pathv' field.  Unlike the other
          fields, this is always an input to `glob', rather than an
          output from it.

          If you use a nonzero offset, then that many elements at the
          beginning of the vector are left empty.  (The `glob' function
          fills them with null pointers.)

          The `gl_offs' field is meaningful only if you use the
          `GLOB_DOOFFS' flag.  Otherwise, the offset is always zero
          regardless of what is in this field, and the first real
          element comes at the beginning of the vector.

    `gl_closedir'
          The address of an alternative implementation of the `closedir'
          function.  It is used if the `GLOB_ALTDIRFUNC' bit is set in
          the flag parameter.  The type of this field is
          `void (*) (void *)'.

          This is a GNU extension.

    `gl_readdir'
          The address of an alternative implementation of the `readdir'
          function used to read the contents of a directory.  It is
          used if the `GLOB_ALTDIRFUNC' bit is set in the flag
          parameter.  The type of this field is
          `struct dirent *(*) (void *)'.

          This is a GNU extension.

    `gl_opendir'
          The address of an alternative implementation of the `opendir'
          function.  It is used if the `GLOB_ALTDIRFUNC' bit is set in
          the flag parameter.  The type of this field is
          `void *(*) (const char *)'.

          This is a GNU extension.

    `gl_stat'
          The address of an alternative implementation of the `stat'
          function to get information about an object in the
          filesystem.  It is used if the `GLOB_ALTDIRFUNC' bit is set
          in the flag parameter.  The type of this field is
          `int (*) (const char *, struct stat *)'.

          This is a GNU extension.

    `gl_lstat'
          The address of an alternative implementation of the `lstat'
          function to get information about an object in the
          filesystems, not following symbolic links.  It is used if the
          `GLOB_ALTDIRFUNC' bit is set in the flag parameter.  The type
          of this field is `int (*) (const char *, struct stat *)'.

          This is a GNU extension.

 - Function: int glob (const char *PATTERN, int FLAGS, int (*ERRFUNC)
          (const char *FILENAME, int ERROR-CODE), glob_t *VECTOR-PTR)
     The function `glob' does globbing using the pattern PATTERN in the
     current directory.  It puts the result in a newly allocated
     vector, and stores the size and address of this vector into
     `*VECTOR-PTR'.  The argument FLAGS is a combination of bit flags;
     see Flags for Globbing, for details of the flags.

     The result of globbing is a sequence of file names.  The function
     `glob' allocates a string for each resulting word, then allocates
     a vector of type `char **' to store the addresses of these
     strings.  The last element of the vector is a null pointer.  This
     vector is called the "word vector".

     To return this vector, `glob' stores both its address and its
     length (number of elements, not counting the terminating null
     pointer) into `*VECTOR-PTR'.

     Normally, `glob' sorts the file names alphabetically before
     returning them.  You can turn this off with the flag `GLOB_NOSORT'
     if you want to get the information as fast as possible.  Usually
     it's a good idea to let `glob' sort them--if you process the files
     in alphabetical order, the users will have a feel for the rate of
     progress that your application is making.

     If `glob' succeeds, it returns 0.  Otherwise, it returns one of
     these error codes:

    `GLOB_ABORTED'
          There was an error opening a directory, and you used the flag
          `GLOB_ERR' or your specified ERRFUNC returned a nonzero value.
          See Flags for Globbing, for an explanation of the
          `GLOB_ERR' flag and ERRFUNC.

    `GLOB_NOMATCH'
          The pattern didn't match any existing files.  If you use the
          `GLOB_NOCHECK' flag, then you never get this error code,
          because that flag tells `glob' to _pretend_ that the pattern
          matched at least one file.

    `GLOB_NOSPACE'
          It was impossible to allocate memory to hold the result.

     In the event of an error, `glob' stores information in
     `*VECTOR-PTR' about all the matches it has found so far.

Flags for Globbing
------------------

   This section describes the flags that you can specify in the FLAGS
argument to `glob'.  Choose the flags you want, and combine them with
the C bitwise OR operator `|'.

`GLOB_APPEND'
     Append the words from this expansion to the vector of words
     produced by previous calls to `glob'.  This way you can
     effectively expand several words as if they were concatenated with
     spaces between them.

     In order for appending to work, you must not modify the contents
     of the word vector structure between calls to `glob'.  And, if you
     set `GLOB_DOOFFS' in the first call to `glob', you must also set
     it when you append to the results.

     Note that the pointer stored in `gl_pathv' may no longer be valid
     after you call `glob' the second time, because `glob' might have
     relocated the vector.  So always fetch `gl_pathv' from the
     `glob_t' structure after each `glob' call; *never* save the
     pointer across calls.

`GLOB_DOOFFS'
     Leave blank slots at the beginning of the vector of words.  The
     `gl_offs' field says how many slots to leave.  The blank slots
     contain null pointers.

`GLOB_ERR'
     Give up right away and report an error if there is any difficulty
     reading the directories that must be read in order to expand
     PATTERN fully.  Such difficulties might include a directory in
     which you don't have the requisite access.  Normally, `glob' tries
     its best to keep on going despite any errors, reading whatever
     directories it can.

     You can exercise even more control than this by specifying an
     error-handler function ERRFUNC when you call `glob'.  If ERRFUNC
     is not a null pointer, then `glob' doesn't give up right away when
     it can't read a directory; instead, it calls ERRFUNC with two
     arguments, like this:

          (*ERRFUNC) (FILENAME, ERROR-CODE)

     The argument FILENAME is the name of the directory that `glob'
     couldn't open or couldn't read, and ERROR-CODE is the `errno'
     value that was reported to `glob'.

     If the error handler function returns nonzero, then `glob' gives up
     right away.  Otherwise, it continues.

`GLOB_MARK'
     If the pattern matches the name of a directory, append `/' to the
     directory's name when returning it.

`GLOB_NOCHECK'
     If the pattern doesn't match any file names, return the pattern
     itself as if it were a file name that had been matched.
     (Normally, when the pattern doesn't match anything, `glob' returns
     that there were no matches.)

`GLOB_NOSORT'
     Don't sort the file names; return them in no particular order.
     (In practice, the order will depend on the order of the entries in
     the directory.)  The only reason _not_ to sort is to save time.

`GLOB_NOESCAPE'
     Don't treat the `\' character specially in patterns.  Normally,
     `\' quotes the following character, turning off its special meaning
     (if any) so that it matches only itself.  When quoting is enabled,
     the pattern `\?' matches only the string `?', because the question
     mark in the pattern acts like an ordinary character.

     If you use `GLOB_NOESCAPE', then `\' is an ordinary character.

     `glob' does its work by calling the function `fnmatch' repeatedly.
     It handles the flag `GLOB_NOESCAPE' by turning on the
     `FNM_NOESCAPE' flag in calls to `fnmatch'.