   This file documents the GNU C library.

   This is Edition 0.06 DRAFT, last updated 24 October 1994, of `The
GNU C Library Reference Manual', for Version 1.09 Beta.

   Copyright (C) 1993, 1994 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 translations of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

Noncanonical Mode Example
=========================

   Here is an example program that shows how you can set up a terminal
device to read single characters in noncanonical input mode, without
echo.

     #include <unistd.h>
     #include <stdio.h>
     #include <stdlib.h>
     #include <termios.h>

     /* Use this variable to remember original terminal attributes. */

     struct termios saved_attributes;

     void
     reset_input_mode (void)
     {
       tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
     }

     void
     set_input_mode (void)
     {
       struct termios tattr;
       char *name;

       /* Make sure stdin is a terminal. */
       if (!isatty (STDIN_FILENO))
         {
           fprintf (stderr, "Not a terminal.\n");
           exit (EXIT_FAILURE);
         }

       /* Save the terminal attributes so we can restore them later. */
       tcgetattr (STDIN_FILENO, &saved_attributes);
       atexit (reset_input_mode);
     /* Set the funny terminal modes. */
       tcgetattr (STDIN_FILENO, &tattr);
       tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
       tattr.c_cc[VMIN] = 1;
       tattr.c_cc[VTIME] = 0;
       tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
     }

     int
     main (void)
     {
       char c;

       set_input_mode ();

       while (1)
         {
           read (STDIN_FILENO, &c, 1);
           if (c == '\004')          /* `C-d' */
             break;
           else
             putchar (c);
         }

       return EXIT_SUCCESS;
     }

   This program is careful to restore the original terminal modes before
exiting or terminating with a signal.  It uses the `atexit' function
(see Cleanups on Exit.) to make sure this is done by `exit'.

   The shell is supposed to take care of resetting the terminal modes
when a process is stopped or continued; see Job Control.  But
some existing shells do not actually do this, so you may wish to
establish handlers for job control signals that reset terminal modes.
The above example does so.

Mathematics
***********

   This chapter contains information about functions for performing
mathematical computations, such as trigonometric functions.  Most of
these functions have prototypes declared in the header file `math.h'.

   All of the functions that operate on floating-point numbers accept
arguments and return results of type `double'.  In the future, there
may be additional functions that operate on `float' and `long double'
values.  For example, `cosf' and `cosl' would be versions of the `cos'
function that operate on `float' and `long double' arguments,
respectively.  In the meantime, you should avoid using these names
yourself.  See Reserved Names.

Domain and Range Errors
=======================

   Many of the functions listed in this chapter are defined
mathematically over a domain that is only a subset of real numbers.
For example, the `acos' function is defined over the domain between
`-1' and `1'.  If you pass an argument to one of these functions that is
outside the domain over which it is defined, the function sets `errno'
to `EDOM' to indicate a "domain error".  On machines that support IEEE
floating point, functions reporting error `EDOM' also return a NaN.

   Some of these functions are defined mathematically to result in a
complex value over parts of their domains.  The most familiar example of
this is taking the square root of a negative number.  The functions in
this chapter take only real arguments and return only real values;
therefore, if the value ought to be nonreal, this is treated as a domain
error.

   A related problem is that the mathematical result of a function may
not be representable as a floating point number.  If magnitude of the
correct result is too large to be represented, the function sets
`errno' to `ERANGE' to indicate a "range error", and returns a
particular very large value (named by the macro `HUGE_VAL') or its
negation (`- HUGE_VAL').

   If the magnitude of the result is too small, a value of zero is
returned instead.  In this case, `errno' might or might not be set to
`ERANGE'.

   The only completely reliable way to check for domain and range
errors is to set `errno' to `0' before you call the mathematical
function and test `errno' afterward.  As a consequence of this use of
`errno', use of the mathematical functions is not reentrant if you
check for errors.

   None of the mathematical functions ever generates signals as a
result of domain or range errors.  In particular, this means that you
won't see `SIGFPE' signals generated within these functions.  (see
Signal Handling, for more information about signals.)

 - Macro: double HUGE_VAL
     An expression representing a particular very large number.  On
     machines that use IEEE floating point format, the value is
     "infinity".  On other machines, it's typically the largest
     positive number that can be represented.

     The value of this macro is used as the return value from various
     mathematical functions in overflow situations.

   For more information about floating-point representations and limits,
see Floating Point Parameters.  In particular, the macro
`DBL_MAX' might be more appropriate than `HUGE_VAL' for many uses other
than testing for an error in a mathematical function.

Trigonometric Functions
=======================

   These are the familiar `sin', `cos', and `tan' functions.  The
arguments to all of these functions are in units of radians; recall
that pi radians equals 180 degrees.

   The math library doesn't define a symbolic constant for pi, but you
can define your own if you need one:

     #define PI 3.14159265358979323846264338327

You can also compute the value of pi with the expression `acos (-1.0)'.

 - Function: double sin (double X)
     This function returns the sine of X, where X is given in radians.
     The return value is in the range `-1' to `1'.

 - Function: double cos (double X)
     This function returns the cosine of X, where X is given in
     radians.  The return value is in the range `-1' to `1'.

 - Function: double tan (double X)
     This function returns the tangent of X, where X is given in
     radians.

     The following `errno' error conditions are defined for this
     function:

    `ERANGE'
          Mathematically, the tangent function has singularities at odd
          multiples of pi/2.  If the argument X is too close to one of
          these singularities, `tan' sets `errno' to `ERANGE' and
          returns either positive or negative `HUGE_VAL'.

Inverse Trigonometric Functions
===============================

   These are the usual arc sine, arc cosine and arc tangent functions,
which are the inverses of the sine, cosine and tangent functions,
respectively.

 - Function: double asin (double X)
     This function computes the arc sine of X--that is, the value whose
     sine is X.  The value is in units of radians.  Mathematically,
     there are infinitely many such values; the one actually returned
     is the one between `-pi/2' and `pi/2' (inclusive).

     `asin' fails, and sets `errno' to `EDOM', if X is out of range.
     The arc sine function is defined mathematically only over the
     domain `-1' to `1'.

 - Function: double acos (double X)
     This function computes the arc cosine of X--that is, the value
     whose cosine is X.  The value is in units of radians.
     Mathematically, there are infinitely many such values; the one
     actually returned is the one between `0' and `pi' (inclusive).

     `acos' fails, and sets `errno' to `EDOM', if X is out of range.
     The arc cosine function is defined mathematically only over the
     domain `-1' to `1'.

 - Function: double atan (double X)
     This function computes the arc tangent of X--that is, the value
     whose tangent is X.  The value is in units of radians.
     Mathematically, there are infinitely many such values; the one
     actually returned is the one between `-pi/2' and `pi/2'
     (inclusive).

 - Function: double atan2 (double Y, double X)
     This is the two argument arc tangent function.  It is similar to
     computing the arc tangent of Y/X, except that the signs of both
     arguments are used to determine the quadrant of the result, and X
     is permitted to be zero.  The return value is given in radians and
     is in the range `-pi' to `pi', inclusive.

     If X and Y are coordinates of a point in the plane, `atan2'
     returns the signed angle between the line from the origin to that
     point and the x-axis.  Thus, `atan2' is useful for converting
     Cartesian coordinates to polar coordinates.  (To compute the
     radial coordinate, use `hypot'; see Exponents and Logarithms.)

     The function `atan2' sets `errno' to `EDOM' if both X and Y are
     zero; the return value is not defined in this case.

Exponentiation and Logarithms
=============================

 - Function: double exp (double X)
     The `exp' function returns the value of e (the base of natural
     logarithms) raised to power X.

     The function fails, and sets `errno' to `ERANGE', if the magnitude
     of the result is too large to be representable.

 - Function: double log (double X)
     This function returns the natural logarithm of X.  `exp (log (X))'
     equals X, exactly in mathematics and approximately in C.

     The following `errno' error conditions are defined for this
     function:

    `EDOM'
          The argument X is negative.  The log function is defined
          mathematically to return a real result only on positive
          arguments.

    `ERANGE'
          The argument is zero.  The log of zero is not defined.

 - Function: double log10 (double X)
     This function returns the base-10 logarithm of X.  Except for the
     different base, it is similar to the `log' function.  In fact,
     `log10 (X)' equals `log (X) / log (10)'.

 - Function: double pow (double BASE, double POWER)
     This is a general exponentiation function, returning BASE raised
     to POWER.

     The following `errno' error conditions are defined for this
     function:

    `EDOM'
          The argument BASE is negative and POWER is not an integral
          value.  Mathematically, the result would be a complex number
          in this case.

    `ERANGE'
          An underflow or overflow condition was detected in the result.

 - Function: double sqrt (double X)
     This function returns the nonnegative square root of X.

     The `sqrt' function fails, and sets `errno' to `EDOM', if X is
     negative.  Mathematically, the square root would be a complex
     number.

 - Function: double cbrt (double X)
     This function returns the cube root of X.  This function cannot
     fail; every representable real value has a representable real cube
     root.

 - Function: double hypot (double X, double Y)
     The `hypot' function returns `sqrt (X*X + Y*Y)'.  (This is the
     length of the hypotenuse of a right triangle with sides of length
     X and Y, or the distance of the point (X, Y) from the origin.)
     See also the function `cabs' in Absolute Value.

 - Function: double expm1 (double X)
     This function returns a value equivalent to `exp (X) - 1'.  It is
     computed in a way that is accurate even if the value of X is near
     zero--a case where `exp (X) - 1' would be inaccurate due to
     subtraction of two numbers that are nearly equal.

 - Function: double log1p (double X)
     This function returns a value equivalent to `log (1 + X)'.  It is
     computed in a way that is accurate even if the value of X is near
     zero.

Hyperbolic Functions
====================

   The functions in this section are related to the exponential
functions; see Exponents and Logarithms.

 - Function: double sinh (double X)
     The `sinh' function returns the hyperbolic sine of X, defined
     mathematically as `exp (X) - exp (-X) / 2'.  The function fails,
     and sets `errno' to `ERANGE', if the value of X is too large; that
     is, if overflow occurs.

 - Function: double cosh (double X)
     The `cosh' function returns the hyperbolic cosine of X, defined
     mathematically as `exp (X) + exp (-X) / 2'.  The function fails,
     and sets `errno' to `ERANGE', if the value of X is too large; that
     is, if overflow occurs.

 - Function: double tanh (double X)
     This function returns the hyperbolic tangent of X, whose
     mathematical definition is `sinh (X) / cosh (X)'.

 - Function: double asinh (double X)
     This function returns the inverse hyperbolic sine of X--the value
     whose hyperbolic sine is X.

 - Function: double acosh (double X)
     This function returns the inverse hyperbolic cosine of X--the
     value whose hyperbolic cosine is X.  If X is less than `1',
     `acosh' returns `HUGE_VAL'.

 - Function: double atanh (double X)
     This function returns the inverse hyperbolic tangent of X--the
     value whose hyperbolic tangent is X.  If the absolute value of X
     is greater than or equal to `1', `atanh' returns `HUGE_VAL'.

Pseudo-Random Numbers
=====================

   This section describes the GNU facilities for generating a series of
pseudo-random numbers.  The numbers generated are not truly random;
typically, they form a sequence that repeats periodically, with a
period so large that you can ignore it for ordinary purposes.  The
random number generator works by remembering at all times a "seed"
value which it uses to compute the next random number and also to
compute a new seed.

   Although the generated numbers look unpredictable within one run of a
program, the sequence of numbers is *exactly the same* from one run to
the next.  This is because the initial seed is always the same.  This
is convenient when you are debugging a program, but it is unhelpful if
you want the program to behave unpredictably.  If you want truly random
numbers, not just pseudo-random, specify a seed based on the current
time.

   You can get repeatable sequences of numbers on a particular machine
type by specifying the same initial seed value for the random number
generator.  There is no standard meaning for a particular seed value;
the same seed, used in different C libraries or on different CPU types,
will give you different random numbers.

   The GNU library supports the standard ANSI C random number functions
plus another set derived from BSD.  We recommend you use the standard
ones, `rand' and `srand'.

ANSI C Random Number Functions
------------------------------

   This section describes the random number functions that are part of
the ANSI C standard.

   To use these facilities, you should include the header file
`stdlib.h' in your program.

 - Macro: int RAND_MAX
     The value of this macro is an integer constant expression that
     represents the maximum possible value returned by the `rand'
     function.  In the GNU library, it is `037777777', which is the
     largest signed integer representable in 32 bits.  In other
     libraries, it may be as low as `32767'.

 - Function: int rand ()
     The `rand' function returns the next pseudo-random number in the
     series.  The value is in the range from `0' to `RAND_MAX'.

 - Function: void srand (unsigned int SEED)
     This function establishes SEED as the seed for a new series of
     pseudo-random numbers.  If you call `rand' before a seed has been
     established with `srand', it uses the value `1' as a default seed.

     To produce truly random numbers (not just pseudo-random), do `srand
     (time (0))'.

BSD Random Number Functions
---------------------------

   This section describes a set of random number generation functions
that are derived from BSD.  There is no advantage to using these
functions with the GNU C library; we support them for BSD compatibility
only.

   The prototypes for these functions are in `stdlib.h'.

 - Function: long int random ()
     This function returns the next pseudo-random number in the
     sequence.  The range of values returned is from `0' to `RAND_MAX'.

 - Function: void srandom (unsigned int SEED)
     The `srandom' function sets the seed for the current random number
     state based on the integer SEED.  If you supply a SEED value of
     `1', this will cause `random' to reproduce the default set of
     random numbers.

     To produce truly random numbers (not just pseudo-random), do
     `srandom (time (0))'.

 - Function: void * initstate (unsigned int SEED, void *STATE, size_t
          SIZE)
     The `initstate' function is used to initialize the random number
     generator state.  The argument STATE is an array of SIZE bytes,
     used to hold the state information.  The size must be at least 8
     bytes, and optimal sizes are 8, 16, 32, 64, 128, and 256.  The
     bigger the STATE array, the better.

     The return value is the previous value of the state information
     array.  You can use this value later as an argument to `setstate'
     to restore that state.

 - Function: void * setstate (void *STATE)
     The `setstate' function restores the random number state
     information STATE.  The argument must have been the result of a
     previous call to INITSTATE or SETSTATE.

     The return value is the previous value of the state information
     array.  You can use thise value later as an argument to `setstate'
     to restore that state.

Low-Level Arithmetic Functions
******************************

   This chapter contains information about functions for doing basic
arithmetic operations, such as splitting a float into its integer and
fractional parts.  These functions are declared in the header file
`math.h'.

"Not a Number" Values
=====================

   The IEEE floating point format used by most modern computers supports
values that are "not a number".  These values are called "NaNs".  "Not
a number" values result from certain operations which have no
meaningful numeric result, such as zero divided by zero or infinity
divided by infinity.

   One noteworthy property of NaNs is that they are not equal to
themselves.  Thus, `x == x' can be 0 if the value of `x' is a NaN.  You
can use this to test whether a value is a NaN or not: if it is not
equal to itself, then it is a NaN.  But the recommended way to test for
a NaN is with the `isnan' function (see Predicates on Floats.).

   Almost any arithmetic operation in which one argument is a NaN
returns a NaN.

 - Macro: double NAN
     An expression representing a value which is "not a number".  This
     macro is a GNU extension, available only on machines that support
     "not a number" values--that is to say, on all machines that
     support IEEE floating point.

     You can use `#ifdef NAN' to test whether the machine supports
     NaNs.  (Of course, you must arrange for GNU extensions to be
     visible, such as by defining `_GNU_SOURCE', and then you must
     include `math.h'.)

Predicates on Floats
====================

   This section describes some miscellaneous test functions on doubles.
Prototypes for these functions appear in `math.h'.  These are BSD
functions, and thus are available if you define `_BSD_SOURCE' or
`_GNU_SOURCE'.

 - Function: int isinf (double X)
     This function returns `-1' if X represents negative infinity, `1'
     if X represents positive infinity, and `0' otherwise.

 - Function: int isnan (double X)
     This function returns a nonzero value if X is a "not a number"
     value, and zero otherwise.  (You can just as well use `X != X' to
     get the same result).

 - Function: int finite (double X)
     This function returns a nonzero value if X is finite or a "not a
     number" value, and zero otherwise.

 - Function: double infnan (int ERROR)
     This function is provided for compatibility with BSD.  The other
     mathematical functions use `infnan' to decide what to return on
     occasion of an error.  Its argument is an error code, `EDOM' or
     `ERANGE'; `infnan' returns a suitable value to indicate this with.
     `-ERANGE' is also acceptable as an argument, and corresponds to
     `-HUGE_VAL' as a value.

     In the BSD library, on certain machines, `infnan' raises a fatal
     signal in all cases.  The GNU library does not do likewise,
     because that does not fit the ANSI C specification.

   *Portability Note:* The functions listed in this section are BSD
extensions.

Absolute Value
==============

   These functions are provided for obtaining the "absolute value" (or
"magnitude") of a number.  The absolute value of a real number X is X
is X is positive, -X if X is negative.  For a complex number Z, whose
real part is X and whose imaginary part is Y, the absolute value is
`sqrt (X*X + Y*Y)'.

   Prototypes for `abs' and `labs' are in `stdlib.h'; `fabs' and `cabs'
are declared in `math.h'.

 - Function: int abs (int NUMBER)
     This function returns the absolute value of NUMBER.

     Most computers use a two's complement integer representation, in
     which the absolute value of `INT_MIN' (the smallest possible `int')
     cannot be represented; thus, `abs (INT_MIN)' is not defined.

 - Function: long int labs (long int NUMBER)
     This is similar to `abs', except that both the argument and result
     are of type `long int' rather than `int'.

 - Function: double fabs (double NUMBER)
     This function returns the absolute value of the floating-point
     number NUMBER.

 - Function: double cabs (struct { double real, imag; } Z)
     The `cabs' function returns the absolute value of the complex
     number Z, whose real part is `Z.real' and whose imaginary part is
     `Z.imag'.  (See also the function `hypot' in Exponents and Logarithms.)
     The value is:

          sqrt (Z.real*Z.real + Z.imag*Z.imag)

Normalization Functions
=======================

   The functions described in this section are primarily provided as a
way to efficiently perform certain low-level manipulations on floating
point numbers that are represented internally using a binary radix; see
Floating Point Concepts.  These functions are required to have
equivalent behavior even if the representation does not use a radix of
2, but of course they are unlikely to be particularly efficient in
those cases.

   All these functions are declared in `math.h'.

 - Function: double frexp (double VALUE, int *EXPONENT)
     The `frexp' function is used to split the number VALUE into a
     normalized fraction and an exponent.

     If the argument VALUE is not zero, the return value is VALUE times
     a power of two, and is always in the range 1/2 (inclusive) to 1
     (exclusive).  The corresponding exponent is stored in `*EXPONENT';
     the return value multiplied by 2 raised to this exponent equals
     the original number VALUE.

     For example, `frexp (12.8, &exponent)' returns `0.8' and stores
     `4' in `exponent'.

     If VALUE is zero, then the return value is zero and zero is stored
     in `*EXPONENT'.

 - Function: double ldexp (double VALUE, int EXPONENT)
     This function returns the result of multiplying the floating-point
     number VALUE by 2 raised to the power EXPONENT.  (It can be used
     to reassemble floating-point numbers that were taken apart by
     `frexp'.)

     For example, `ldexp (0.8, 4)' returns `12.8'.

   The following functions which come from BSD provide facilities
equivalent to those of `ldexp' and `frexp':

 - Function: double scalb (double VALUE, int EXPONENT)
     The `scalb' function is the BSD name for `ldexp'.

 - Function: double logb (double X)
     This BSD function returns the integer part of the base-2 logarithm
     of X, an integer value represented in type `double'.  This is the
     highest integer power of `2' contained in X.  The sign of X is
     ignored.  For example, `logb (3.5)' is `1.0' and `logb (4.0)' is
     `2.0'.

     When `2' raised to this power is divided into X, it gives a
     quotient between `1' (inclusive) and `2' (exclusive).

     If X is zero, the value is minus infinity (if the machine supports
     such a value), or else a very small number.  If X is infinity, the
     value is infinity.

     The value returned by `logb' is one less than the value that
     `frexp' would store into `*EXPONENT'.

 - Function: double copysign (double VALUE, double SIGN)
     The `copysign' function returns a value whose absolute value is the
     same as that of VALUE, and whose sign matches that of SIGN.  This
     is a BSD function.

Rounding and Remainder Functions
================================

   The functions listed here perform operations such as rounding,
truncation, and remainder in division of floating point numbers.  Some
of these functions convert floating point numbers to integer values.
They are all declared in `math.h'.

   You can also convert floating-point numbers to integers simply by
casting them to `int'.  This discards the fractional part, effectively
rounding towards zero.  However, this only works if the result can
actually be represented as an `int'--for very large numbers, this is
impossible.  The functions listed here return the result as a `double'
instead to get around this problem.

 - Function: double ceil (double X)
     The `ceil' function rounds X upwards to the nearest integer,
     returning that value as a `double'.  Thus, `ceil (1.5)' is `2.0'.

 - Function: double floor (double X)
     The `ceil' function rounds X downwards to the nearest integer,
     returning that value as a `double'.  Thus, `floor (1.5)' is `1.0'
     and `floor (-1.5)' is `-2.0'.

 - Function: double rint (double X)
     This function rounds X to an integer value according to the
     current rounding mode.  See Floating Point Parameters, for
     information about the various rounding modes.  The default
     rounding mode is to round to the nearest integer; some machines
     support other modes, but round-to-nearest is always used unless
     you explicit select another.

 - Function: double modf (double VALUE, double *INTEGER-PART)
     This function breaks the argument VALUE into an integer part and a
     fractional part (between `-1' and `1', exclusive).  Their sum
     equals VALUE.  Each of the parts has the same sign as VALUE, so
     the rounding of the integer part is towards zero.

     `modf' stores the integer part in `*INTEGER-PART', and returns the
     fractional part.  For example, `modf (2.5, &intpart)' returns
     `0.5' and stores `2.0' into `intpart'.

 - Function: double fmod (double NUMERATOR, double DENOMINATOR)
     This function computes the remainder from the division of
     NUMERATOR by DENOMINATOR.  Specifically, the return value is
     `NUMERATOR - N * DENOMINATOR', where N is the quotient of
     NUMERATOR divided by DENOMINATOR, rounded towards zero to an
     integer.  Thus, `fmod (6.5, 2.3)' returns `1.9', which is `6.5'
     minus `4.6'.

     The result has the same sign as the NUMERATOR and has magnitude
     less than the magnitude of the DENOMINATOR.

     If DENOMINATOR is zero, `fmod' fails and sets `errno' to `EDOM'.

 - Function: double drem (double NUMERATOR, double DENOMINATOR)
     The function `drem' is like `fmod' except that it rounds the
     internal quotient N to the nearest integer instead of towards zero
     to an integer.  For example, `drem (6.5, 2.3)' returns `-0.4',
     which is `6.5' minus `6.9'.

     The absolute value of the result is less than or equal to half the
     absolute value of the DENOMINATOR.  The difference between `fmod
     (NUMERATOR, DENOMINATOR)' and `drem (NUMERATOR, DENOMINATOR)' is
     always either DENOMINATOR, minus DENOMINATOR, or zero.

     If DENOMINATOR is zero, `drem' fails and sets `errno' to `EDOM'.

Integer Division
================

   This section describes functions for performing integer division.
These functions are redundant in the GNU C library, since in GNU C the
`/' operator always rounds towards zero.  But in other C
implementations, `/' may round differently with negative arguments.
`div' and `ldiv' are useful because they specify how to round the
quotient: towards zero.  The remainder has the same sign as the
numerator.

   These functions are specified to return a result R such that the
value `R.quot*DENOMINATOR + R.rem' equals NUMERATOR.

   To use these facilities, you should include the header file
`stdlib.h' in your program.

 - Data Type: div_t
     This is a structure type used to hold the result returned by the
     `div' function.  It has the following members:

    `int quot'
          The quotient from the division.

    `int rem'
          The remainder from the division.

 - Function: div_t div (int NUMERATOR, int DENOMINATOR)
     This function `div' computes the quotient and remainder from the
     division of NUMERATOR by DENOMINATOR, returning the result in a
     structure of type `div_t'.

     If the result cannot be represented (as in a division by zero), the
     behavior is undefined.

     Here is an example, albeit not a very useful one.

          div_t result;
          result = div (20, -6);

     Now `result.quot' is `-3' and `result.rem' is `2'.

 - Data Type: ldiv_t
     This is a structure type used to hold the result returned by the
     `ldiv' function.  It has the following members:

    `long int quot'
          The quotient from the division.

    `long int rem'
          The remainder from the division.

     (This is identical to `div_t' except that the components are of
     type `long int' rather than `int'.)

 - Function: ldiv_t ldiv (long int NUMERATOR, long int DENOMINATOR)
     The `ldiv' function is similar to `div', except that the arguments
     are of type `long int' and the result is returned as a structure
     of type `ldiv'.

Parsing of Numbers
==================

   This section describes functions for "reading" integer and
floating-point numbers from a string.  It may be more convenient in some
cases to use `sscanf' or one of the related functions; see
Formatted Input.  But often you can make a program more robust by
finding the tokens in the string by hand, then converting the numbers
one by one.

Parsing of Integers
-------------------

   These functions are declared in `stdlib.h'.

 - Function: long int strtol (const char *STRING, char **TAILPTR, int
          BASE)
     The `strtol' ("string-to-long") function converts the initial part
     of STRING to a signed integer, which is returned as a value of
     type `long int'.

     This function attempts to decompose STRING as follows:

        * A (possibly empty) sequence of whitespace characters.  Which
          characters are whitespace is determined by the `isspace'
          function (see Classification of Characters.).  These are
          discarded.

        * An optional plus or minus sign (`+' or `-').

        * A nonempty sequence of digits in the radix specified by BASE.

          If BASE is zero, decimal radix is assumed unless the series of
          digits begins with `0' (specifying octal radix), or `0x' or
          `0X' (specifying hexadecimal radix); in other words, the same
          syntax used for integer constants in C.

          Otherwise BASE must have a value between `2' and `35'.  If
          BASE is `16', the digits may optionally be preceded by `0x'
          or `0X'.

        * Any remaining characters in the string.  If TAILPTR is not a
          null pointer, `strtol' stores a pointer to this tail in
          `*TAILPTR'.

     If the string is empty, contains only whitespace, or does not
     contain an initial substring that has the expected syntax for an
     integer in the specified BASE, no conversion is performed.  In
     this case, `strtol' returns a value of zero and the value stored in
     `*TAILPTR' is the value of STRING.

     In a locale other than the standard `"C"' locale, this function
     may recognize additional implementation-dependent syntax.

     If the string has valid syntax for an integer but the value is not
     representable because of overflow, `strtol' returns either
     `LONG_MAX' or `LONG_MIN' (see Range of Type.), as appropriate
     for the sign of the value.  It also sets `errno' to `ERANGE' to
     indicate there was overflow.

     There is an example at the end of this section.

 - Function: unsigned long int strtoul (const char *STRING, char
          **TAILPTR, int BASE)
     The `strtoul' ("string-to-unsigned-long") function is like
     `strtol' except that it returns its value with type `unsigned long
     int'.  The value returned in case of overflow is `ULONG_MAX'
     (see Range of Type.).

 - Function: long int atol (const char *STRING)
     This function is similar to the `strtol' function with a BASE
     argument of `10', except that it need not detect overflow errors.
     The `atol' function is provided mostly for compatibility with
     existing code; using `strtol' is more robust.

 - Function: int atoi (const char *STRING)
     This function is like `atol', except that it returns an `int'
     value rather than `long int'.  The `atoi' function is also
     considered obsolete; use `strtol' instead.

   Here is a function which parses a string as a sequence of integers
and returns the sum of them:

     int
     sum_ints_from_string (char *string)
     {
       int sum = 0;

       while (1) {
         char *tail;
         int next;

         /* Skip whitespace by hand, to detect the end.  */
         while (isspace (*string)) string++;
         if (*string == 0)
           break;

         /* There is more nonwhitespace,  */
         /* so it ought to be another number.  */
         errno = 0;
         /* Parse it.  */
         next = strtol (string, &tail, 0);
         /* Add it in, if not overflow.  */
         if (errno)
           printf ("Overflow\n");
         else
           sum += next;
         /* Advance past it.  */
         string = tail;
       }

       return sum;
     }

Parsing of Floats
-----------------

   These functions are declared in `stdlib.h'.

 - Function: double strtod (const char *STRING, char **TAILPTR)
     The `strtod' ("string-to-double") function converts the initial
     part of STRING to a floating-point number, which is returned as a
     value of type `double'.

     This function attempts to decompose STRING as follows:

        * A (possibly empty) sequence of whitespace characters.  Which
          characters are whitespace is determined by the `isspace'
          function (see Classification of Characters.).  These are
          discarded.

        * An optional plus or minus sign (`+' or `-').

        * A nonempty sequence of digits optionally containing a
          decimal-point character--normally `.', but it depends on the
          locale (see Numeric Formatting.).

        * An optional exponent part, consisting of a character `e' or
          `E', an optional sign, and a sequence of digits.

        * Any remaining characters in the string.  If TAILPTR is not a
          null pointer, a pointer to this tail of the string is stored
          in `*TAILPTR'.

     If the string is empty, contains only whitespace, or does not
     contain an initial substring that has the expected syntax for a
     floating-point number, no conversion is performed.  In this case,
     `strtod' returns a value of zero and the value returned in
     `*TAILPTR' is the value of STRING.

     In a locale other than the standard `"C"' locale, this function may
     recognize additional locale-dependent syntax.

     If the string has valid syntax for a floating-point number but the
     value is not representable because of overflow, `strtod' returns
     either positive or negative `HUGE_VAL' (see Mathematics.),
     depending on the sign of the value.  Similarly, if the value is
     not representable because of underflow, `strtod' returns zero.  It
     also sets `errno' to `ERANGE' if there was overflow or underflow.

 - Function: double atof (const char *STRING)
     This function is similar to the `strtod' function, except that it
     need not detect overflow and underflow errors.  The `atof' function
     is provided mostly for compatibility with existing code; using
     `strtod' is more robust.

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 double *a, const double *b)
     {
       return (int) (*a - *b);
     }

   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
=====================

   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.

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.