   This file documents the GNU C library.

   This is Edition 0.07 DRAFT, last updated 4 Oct 1996, of `The GNU C
Library Reference Manual', for Version 2.00 Beta.

   Copyright (C) 1993, '94, '95, '96, '97 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.

Formatted Output Functions
--------------------------

   This section describes how to call `printf' and related functions.
Prototypes for these functions are in the header file `stdio.h'.
Because these functions take a variable number of arguments, you *must*
declare prototypes for them before using them.  Of course, the easiest
way to make sure you have all the right prototypes is to just include
`stdio.h'.

 - Function: int printf (const char *TEMPLATE, ...)
     The `printf' function prints the optional arguments under the
     control of the template string TEMPLATE to the stream `stdout'.
     It returns the number of characters printed, or a negative value
     if there was an output error.

 - Function: int fprintf (FILE *STREAM, const char *TEMPLATE, ...)
     This function is just like `printf', except that the output is
     written to the stream STREAM instead of `stdout'.

 - Function: int sprintf (char *S, const char *TEMPLATE, ...)
     This is like `printf', except that the output is stored in the
     character array S instead of written to a stream.  A null
     character is written to mark the end of the string.

     The `sprintf' function returns the number of characters stored in
     the array S, not including the terminating null character.

     The behavior of this function is undefined if copying takes place
     between objects that overlap--for example, if S is also given as
     an argument to be printed under control of the `%s' conversion.
     See Copying and Concatenation.

     *Warning:* The `sprintf' function can be *dangerous* because it
     can potentially output more characters than can fit in the
     allocation size of the string S.  Remember that the field width
     given in a conversion specification is only a *minimum* value.

     To avoid this problem, you can use `snprintf' or `asprintf',
     described below.

 - Function: int snprintf (char *S, size_t SIZE, const char *TEMPLATE,
          ...)
     The `snprintf' function is similar to `sprintf', except that the
     SIZE argument specifies the maximum number of characters to
     produce.  The trailing null character is counted towards this
     limit, so you should allocate at least SIZE characters for the
     string S.

     The return value is the number of characters stored, not including
     the terminating null.  If this value equals `SIZE - 1', then there
     was not enough space in S for all the output.  You should try
     again with a bigger output string.  Here is an example of doing
     this:

          /* Construct a message describing the value of a variable
             whose name is NAME and whose value is VALUE. */
          char *
          make_message (char *name, char *value)
          {
            /* Guess we need no more than 100 chars of space. */
            int size = 100;
            char *buffer = (char *) xmalloc (size);

          while (1)
              {
                /* Try to print in the allocated space. */
                int nchars = snprintf (buffer, size,
                                       "value of %s is %s",
                                       name, value);
                /* If that worked, return the string. */
                if (nchars < size)
                  return buffer;
                /* Else try again with twice as much space. */
                size *= 2;
                buffer = (char *) xrealloc (size, buffer);
              }
          }

     In practice, it is often easier just to use `asprintf', below.

Dynamically Allocating Formatted Output
---------------------------------------

   The functions in this section do formatted output and place the
results in dynamically allocated memory.

 - Function: int asprintf (char **PTR, const char *TEMPLATE, ...)
     This function is similar to `sprintf', except that it dynamically
     allocates a string (as with `malloc'; see Unconstrained Allocation.)
     to hold the output, instead of putting the output
     in a buffer you allocate in advance.  The PTR argument should be
     the address of a `char *' object, and `asprintf' stores a pointer
     to the newly allocated string at that location.

     Here is how to use `asprintf' to get the same result as the
     `snprintf' example, but more easily:

          /* Construct a message describing the value of a variable
             whose name is NAME and whose value is VALUE. */
          char *
          make_message (char *name, char *value)
          {
            char *result;
            asprintf (&result, "value of %s is %s", name, value);
            return result;
          }

 - Function: int obstack_printf (struct obstack *OBSTACK, const char
          *TEMPLATE, ...)
     This function is similar to `asprintf', except that it uses the
     obstack OBSTACK to allocate the space.  See Obstacks.

     The characters are written onto the end of the current object.  To
     get at them, you must finish the object with `obstack_finish'
     (see Growing Objects.).

Variable Arguments Output Functions
-----------------------------------

   The functions `vprintf' and friends are provided so that you can
define your own variadic `printf'-like functions that make use of the
same internals as the built-in formatted output functions.

   The most natural way to define such functions would be to use a
language construct to say, "Call `printf' and pass this template plus
all of my arguments after the first five."  But there is no way to do
this in C, and it would be hard to provide a way, since at the C
language level there is no way to tell how many arguments your function
received.

   Since that method is impossible, we provide alternative functions,
the `vprintf' series, which lets you pass a `va_list' to describe "all
of my arguments after the first five."

   When it is sufficient to define a macro rather than a real function,
the GNU C compiler provides a way to do this much more easily with
macros.  For example:

     #define myprintf(a, b, c, d, e, rest...) printf (mytemplate , ## rest...)

See Macros with Variable Numbers of Arguments (gcc.info),
for details.  But this is limited to macros, and does not
apply to real functions at all.

   Before calling `vprintf' or the other functions listed in this
section, you *must* call `va_start' (see Variadic Functions.) to
initialize a pointer to the variable arguments.  Then you can call
`va_arg' to fetch the arguments that you want to handle yourself.  This
advances the pointer past those arguments.

   Once your `va_list' pointer is pointing at the argument of your
choice, you are ready to call `vprintf'.  That argument and all
subsequent arguments that were passed to your function are used by
`vprintf' along with the template that you specified separately.

   In some other systems, the `va_list' pointer may become invalid
after the call to `vprintf', so you must not use `va_arg' after you
call `vprintf'.  Instead, you should call `va_end' to retire the
pointer from service.  However, you can safely call `va_start' on
another pointer variable and begin fetching the arguments again through
that pointer.  Calling `vprintf' does not destroy the argument list of
your function, merely the particular pointer that you passed to it.

   GNU C does not have such restrictions.  You can safely continue to
fetch arguments from a `va_list' pointer after passing it to `vprintf',
and `va_end' is a no-op.  (Note, however, that subsequent `va_arg'
calls will fetch the same arguments which `vprintf' previously used.)

   Prototypes for these functions are declared in `stdio.h'.

 - Function: int vprintf (const char *TEMPLATE, va_list AP)
     This function is similar to `printf' except that, instead of taking
     a variable number of arguments directly, it takes an argument list
     pointer AP.

 - Function: int vfprintf (FILE *STREAM, const char *TEMPLATE, va_list
          AP)
     This is the equivalent of `fprintf' with the variable argument list
     specified directly as for `vprintf'.

 - Function: int vsprintf (char *S, const char *TEMPLATE, va_list AP)
     This is the equivalent of `sprintf' with the variable argument list
     specified directly as for `vprintf'.

 - Function: int vsnprintf (char *S, size_t SIZE, const char *TEMPLATE,
          va_list AP)
     This is the equivalent of `snprintf' with the variable argument
     list specified directly as for `vprintf'.

 - Function: int vasprintf (char **PTR, const char *TEMPLATE, va_list
          AP)
     The `vasprintf' function is the equivalent of `asprintf' with the
     variable argument list specified directly as for `vprintf'.

 - Function: int obstack_vprintf (struct obstack *OBSTACK, const char
          *TEMPLATE, va_list AP)
     The `obstack_vprintf' function is the equivalent of
     `obstack_printf' with the variable argument list specified directly
     as for `vprintf'.

   Here's an example showing how you might use `vfprintf'.  This is a
function that prints error messages to the stream `stderr', along with
a prefix indicating the name of the program (see Error Messages.,
for a description of `program_invocation_short_name').

     #include <stdio.h>
     #include <stdarg.h>

     void
     eprintf (const char *template, ...)
     {
       va_list ap;
       extern char *program_invocation_short_name;

       fprintf (stderr, "%s: ", program_invocation_short_name);
       va_start (ap, count);
       vfprintf (stderr, template, ap);
       va_end (ap);
     }

You could call `eprintf' like this:

     eprintf ("file `%s' does not exist\n", filename);

   In GNU C, there is a special construct you can use to let the
compiler know that a function uses a `printf'-style format string.
Then it can check the number and types of arguments in each call to the
function, and warn you when they do not match the format string.  For
example, take this declaration of `eprintf':

     void eprintf (const char *template, ...)
             __attribute__ ((format (printf, 1, 2)));

This tells the compiler that `eprintf' uses a format string like
`printf' (as opposed to `scanf'; see Formatted Input.); the format
string appears as the first argument; and the arguments to satisfy the
format begin with the second.  See Declaring Attributes of Functions (gcc.info),
for more information.

Parsing a Template String
-------------------------

   You can use the function `parse_printf_format' to obtain information
about the number and types of arguments that are expected by a given
template string.  This function permits interpreters that provide
interfaces to `printf' to avoid passing along invalid arguments from
the user's program, which could cause a crash.

   All the symbols described in this section are declared in the header
file `printf.h'.

 - Function: size_t parse_printf_format (const char *TEMPLATE, size_t
          N, int *ARGTYPES)
     This function returns information about the number and types of
     arguments expected by the `printf' template string TEMPLATE.  The
     information is stored in the array ARGTYPES; each element of this
     array describes one argument.  This information is encoded using
     the various `PA_' macros, listed below.

     The N argument specifies the number of elements in the array
     ARGTYPES.  This is the most elements that `parse_printf_format'
     will try to write.

     `parse_printf_format' returns the total number of arguments
     required by TEMPLATE.  If this number is greater than N, then the
     information returned describes only the first N arguments.  If you
     want information about more than that many arguments, allocate a
     bigger array and call `parse_printf_format' again.

   The argument types are encoded as a combination of a basic type and
modifier flag bits.

 - Macro: int PA_FLAG_MASK
     This macro is a bitmask for the type modifier flag bits.  You can
     write the expression `(argtypes[i] & PA_FLAG_MASK)' to extract
     just the flag bits for an argument, or `(argtypes[i] &
     ~PA_FLAG_MASK)' to extract just the basic type code.

   Here are symbolic constants that represent the basic types; they
stand for integer values.

`PA_INT'
     This specifies that the base type is `int'.

`PA_CHAR'
     This specifies that the base type is `int', cast to `char'.

`PA_STRING'
     This specifies that the base type is `char *', a null-terminated
     string.

`PA_POINTER'
     This specifies that the base type is `void *', an arbitrary
     pointer.

`PA_FLOAT'
     This specifies that the base type is `float'.

`PA_DOUBLE'
     This specifies that the base type is `double'.

`PA_LAST'
     You can define additional base types for your own programs as
     offsets from `PA_LAST'.  For example, if you have data types `foo'
     and `bar' with their own specialized `printf' conversions, you
     could define encodings for these types as:

          #define PA_FOO  PA_LAST
          #define PA_BAR  (PA_LAST + 1)

   Here are the flag bits that modify a basic type.  They are combined
with the code for the basic type using inclusive-or.

`PA_FLAG_PTR'
     If this bit is set, it indicates that the encoded type is a
     pointer to the base type, rather than an immediate value.  For
     example, `PA_INT|PA_FLAG_PTR' represents the type `int *'.

`PA_FLAG_SHORT'
     If this bit is set, it indicates that the base type is modified
     with `short'.  (This corresponds to the `h' type modifier.)

`PA_FLAG_LONG'
     If this bit is set, it indicates that the base type is modified
     with `long'.  (This corresponds to the `l' type modifier.)

`PA_FLAG_LONG_LONG'
     If this bit is set, it indicates that the base type is modified
     with `long long'.  (This corresponds to the `L' type modifier.)

`PA_FLAG_LONG_DOUBLE'
     This is a synonym for `PA_FLAG_LONG_LONG', used by convention with
     a base type of `PA_DOUBLE' to indicate a type of `long double'.

   For an example of using these facilities, see Example of Parsing.

Example of Parsing a Template String
------------------------------------

   Here is an example of decoding argument types for a format string.
We assume this is part of an interpreter which contains arguments of
type `NUMBER', `CHAR', `STRING' and `STRUCTURE' (and perhaps others
which are not valid here).

     /* Test whether the NARGS specified objects
        in the vector ARGS are valid
        for the format string FORMAT:
        if so, return 1.
        If not, return 0 after printing an error message.  */

     int
     validate_args (char *format, int nargs, OBJECT *args)
     {
       int *argtypes;
       int nwanted;

       /* Get the information about the arguments.
          Each conversion specification must be at least two characters
          long, so there cannot be more specifications than half the
          length of the string.  */

       argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
       nwanted = parse_printf_format (string, nelts, argtypes);

       /* Check the number of arguments.  */
       if (nwanted > nargs)
         {
           error ("too few arguments (at least %d required)", nwanted);
           return 0;
         }

       /* Check the C type wanted for each argument
          and see if the object given is suitable.  */
       for (i = 0; i < nwanted; i++)
         {
           int wanted;

           if (argtypes[i] & PA_FLAG_PTR)
             wanted = STRUCTURE;
           else
             switch (argtypes[i] & ~PA_FLAG_MASK)
               {
               case PA_INT:
               case PA_FLOAT:
               case PA_DOUBLE:
                 wanted = NUMBER;
                 break;
               case PA_CHAR:
                 wanted = CHAR;
                 break;
               case PA_STRING:
                 wanted = STRING;
                 break;
               case PA_POINTER:
                 wanted = STRUCTURE;
                 break;
               }
           if (TYPE (args[i]) != wanted)
             {
               error ("type mismatch for arg number %d", i);
               return 0;
             }
         }
       return 1;
     }

Customizing `printf'
====================

   The GNU C library lets you define your own custom conversion
specifiers for `printf' template strings, to teach `printf' clever ways
to print the important data structures of your program.

   The way you do this is by registering the conversion with the
function `register_printf_function'; see Registering New Conversions.
One of the arguments you pass to this function is a
pointer to a handler function that produces the actual output; see
Defining the Output Handler, for information on how to write
this function.

   You can also install a function that just returns information about
the number and type of arguments expected by the conversion specifier.
See Parsing a Template String, for information about this.

   The facilities of this section are declared in the header file
`printf.h'.

   *Portability Note:* The ability to extend the syntax of `printf'
template strings is a GNU extension.  ISO standard C has nothing
similar.

Registering New Conversions
---------------------------

   The function to register a new output conversion is
`register_printf_function', declared in `printf.h'.

 - Function: int register_printf_function (int SPEC, printf_function
          HANDLER-FUNCTION, printf_arginfo_function ARGINFO-FUNCTION)
     This function defines the conversion specifier character SPEC.
     Thus, if SPEC is `'z'', it defines the conversion `%z'.  You can
     redefine the built-in conversions like `%s', but flag characters
     like `#' and type modifiers like `l' can never be used as
     conversions; calling `register_printf_function' for those
     characters has no effect.

     The HANDLER-FUNCTION is the function called by `printf' and
     friends when this conversion appears in a template string.  See
     Defining the Output Handler, for information about how to define
     a function to pass as this argument.  If you specify a null
     pointer, any existing handler function for SPEC is removed.

     The ARGINFO-FUNCTION is the function called by
     `parse_printf_format' when this conversion appears in a template
     string.  See Parsing a Template String, for information about
     this.

     *Attention:* In the GNU C library version before 2.0 the
     ARGINFO-FUNCTION function did not need to be installed unless the
     user uses the `parse_printf_format' function.  This changed.  Now
     a call to any of the `printf' functions will call this function
     when this format specifier appears in the format string.

     The return value is `0' on success, and `-1' on failure (which
     occurs if SPEC is out of range).

     You can redefine the standard output conversions, but this is
     probably not a good idea because of the potential for confusion.
     Library routines written by other people could break if you do
     this.

Conversion Specifier Options
----------------------------

   If you define a meaning for `%A', what if the template contains
`%+23A' or `%-#A'?  To implement a sensible meaning for these, the
handler when called needs to be able to get the options specified in
the template.

   Both the HANDLER-FUNCTION and ARGINFO-FUNCTION arguments to
`register_printf_function' accept an argument that points to a `struct
printf_info', which contains information about the options appearing in
an instance of the conversion specifier.  This data type is declared in
the header file `printf.h'.

 - Type: struct printf_info
     This structure is used to pass information about the options
     appearing in an instance of a conversion specifier in a `printf'
     template string to the handler and arginfo functions for that
     specifier.  It contains the following members:

    `int prec'
          This is the precision specified.  The value is `-1' if no
          precision was specified.  If the precision was given as `*',
          the `printf_info' structure passed to the handler function
          contains the actual value retrieved from the argument list.
          But the structure passed to the arginfo function contains a
          value of `INT_MIN', since the actual value is not known.

    `int width'
          This is the minimum field width specified.  The value is `0'
          if no width was specified.  If the field width was given as
          `*', the `printf_info' structure passed to the handler
          function contains the actual value retrieved from the
          argument list.  But the structure passed to the arginfo
          function contains a value of `INT_MIN', since the actual
          value is not known.

    `wchar_t spec'
          This is the conversion specifier character specified.  It's
          stored in the structure so that you can register the same
          handler function for multiple characters, but still have a
          way to tell them apart when the handler function is called.

    `unsigned int is_long_double'
          This is a boolean that is true if the `L', `ll', or `q' type
          modifier was specified.  For integer conversions, this
          indicates `long long int', as opposed to `long double' for
          floating point conversions.

    `unsigned int is_short'
          This is a boolean that is true if the `h' type modifier was
          specified.

    `unsigned int is_long'
          This is a boolean that is true if the `l' type modifier was
          specified.

    `unsigned int alt'
          This is a boolean that is true if the `#' flag was specified.

    `unsigned int space'
          This is a boolean that is true if the ` ' flag was specified.

    `unsigned int left'
          This is a boolean that is true if the `-' flag was specified.

    `unsigned int showsign'
          This is a boolean that is true if the `+' flag was specified.

    `unsigned int group'
          This is a boolean that is true if the `'' flag was specified.

    `unsigned int extra'
          This flag has a special meaning depending on the context.  It
          could be used freely by the user-defined handlers but when
          called from the `printf' function this variable always
          contains the value `0'.

    `wchar_t pad'
          This is the character to use for padding the output to the
          minimum field width.  The value is `'0'' if the `0' flag was
          specified, and `' '' otherwise.

Defining the Output Handler
---------------------------

   Now let's look at how to define the handler and arginfo functions
which are passed as arguments to `register_printf_function'.

   *Compatibility Note:* The interface change in the GNU libc version
2.0.  Previously the third argument was of type `va_list *'.

   You should define your handler functions with a prototype like:

     int FUNCTION (FILE *stream, const struct printf_info *info,
                         const void *const *args)

   The STREAM argument passed to the handler function is the stream to
which it should write output.

   The INFO argument is a pointer to a structure that contains
information about the various options that were included with the
conversion in the template string.  You should not modify this structure
inside your handler function.  See Conversion Specifier Options, for
a description of this data structure.

   The ARGS is a vector of pointers to the arguments data.  The number
of arguments were determined by calling the argument information
function provided by the user.

   Your handler function should return a value just like `printf' does:
it should return the number of characters it has written, or a negative
value to indicate an error.

 - Data Type: printf_function
     This is the data type that a handler function should have.

   If you are going to use `parse_printf_format' in your application,
you must also define a function to pass as the ARGINFO-FUNCTION
argument for each new conversion you install with
`register_printf_function'.

   You have to define these functions with a prototype like:

     int FUNCTION (const struct printf_info *info,
                         size_t n, int *argtypes)

   The return value from the function should be the number of arguments
the conversion expects.  The function should also fill in no more than
N elements of the ARGTYPES array with information about the types of
each of these arguments.  This information is encoded using the various
`PA_' macros.  (You will notice that this is the same calling
convention `parse_printf_format' itself uses.)

 - Data Type: printf_arginfo_function
     This type is used to describe functions that return information
     about the number and type of arguments used by a conversion
     specifier.

`printf' Extension Example
--------------------------

   Here is an example showing how to define a `printf' handler function.
This program defines a data structure called a `Widget' and defines the
`%W' conversion to print information about `Widget *' arguments,
including the pointer value and the name stored in the data structure.
The `%W' conversion supports the minimum field width and
left-justification options, but ignores everything else.

     #include <stdio.h>
     #include <printf.h>
     #include <stdarg.h>
     typedef struct
       {
         char *name;
       } Widget;

     int
     print_widget (FILE *stream, const struct printf_info *info, va_list *app)
     {
       Widget *w;
       char *buffer;
       int len;

       /* Format the output into a string. */
       w = va_arg (*app, Widget *);
       len = asprintf (&buffer, "<Widget %p: %s>", w, w->name);
       if (len == -1)
         return -1;

       /* Pad to the minimum field width and print to the stream. */
       len = fprintf (stream, "%*s",
                      (info->left ? - info->width : info->width),
                      buffer);

       /* Clean up and return. */
       free (buffer);
       return len;
     }

     int
     print_widget_arginfo (const struct printf_info *info, size_t n,
                           int *argtypes)
     {
       /* We always take exactly one argument and this is a pointer to the
          structure.. */
       if (n > 0)
         argtypes[0] = PA_POINTER;
       return 1;
     }

     int
     main (void)
     {
       /* Make a widget to print. */
       Widget mywidget;
       mywidget.name = "mywidget";

       /* Register the print function for widgets. */
       register_printf_function ('W', print_widget, print_widget_arginfo);

       /* Now print the widget. */
       printf ("|%W|\n", &mywidget);
       printf ("|%35W|\n", &mywidget);
       printf ("|%-35W|\n", &mywidget);

       return 0;
     }

   The output produced by this program looks like:

     |<Widget 0xffeffb7c: mywidget>|
     |      <Widget 0xffeffb7c: mywidget>|
     |<Widget 0xffeffb7c: mywidget>      |

Formatted Input
===============

   The functions described in this section (`scanf' and related
functions) provide facilities for formatted input analogous to the
formatted output facilities.  These functions provide a mechanism for
reading arbitrary values under the control of a "format string" or
"template string".

Formatted Input Basics
----------------------

   Calls to `scanf' are superficially similar to calls to `printf' in
that arbitrary arguments are read under the control of a template
string.  While the syntax of the conversion specifications in the
template is very similar to that for `printf', the interpretation of
the template is oriented more towards free-format input and simple
pattern matching, rather than fixed-field formatting.  For example,
most `scanf' conversions skip over any amount of "white space"
(including spaces, tabs, and newlines) in the input file, and there is
no concept of precision for the numeric input conversions as there is
for the corresponding output conversions.  Ordinarily, non-whitespace
characters in the template are expected to match characters in the
input stream exactly, but a matching failure is distinct from an input
error on the stream.

   Another area of difference between `scanf' and `printf' is that you
must remember to supply pointers rather than immediate values as the
optional arguments to `scanf'; the values that are read are stored in
the objects that the pointers point to.  Even experienced programmers
tend to forget this occasionally, so if your program is getting strange
errors that seem to be related to `scanf', you might want to
double-check this.

   When a "matching failure" occurs, `scanf' returns immediately,
leaving the first non-matching character as the next character to be
read from the stream.  The normal return value from `scanf' is the
number of values that were assigned, so you can use this to determine if
a matching error happened before all the expected values were read.

   The `scanf' function is typically used for things like reading in
the contents of tables.  For example, here is a function that uses
`scanf' to initialize an array of `double':

     void
     readarray (double *array, int n)
     {
       int i;
       for (i=0; i<n; i++)
         if (scanf (" %lf", &(array[i])) != 1)
           invalid_input_error ();
     }

   The formatted input functions are not used as frequently as the
formatted output functions.  Partly, this is because it takes some care
to use them properly.  Another reason is that it is difficult to recover
from a matching error.

   If you are trying to read input that doesn't match a single, fixed
pattern, you may be better off using a tool such as Flex to generate a
lexical scanner, or Bison to generate a parser, rather than using
`scanf'.  For more information about these tools, see flex.info,
and bison.info.

Input Conversion Syntax
-----------------------

   A `scanf' template string is a string that contains ordinary
multibyte characters interspersed with conversion specifications that
start with `%'.

   Any whitespace character (as defined by the `isspace' function;
see Classification of Characters.) in the template causes any number
of whitespace characters in the input stream to be read and discarded.
The whitespace characters that are matched need not be exactly the same
whitespace characters that appear in the template string.  For example,
write ` , ' in the template to recognize a comma with optional
whitespace before and after.

   Other characters in the template string that are not part of
conversion specifications must match characters in the input stream
exactly; if this is not the case, a matching failure occurs.

   The conversion specifications in a `scanf' template string have the
general form:

     % FLAGS WIDTH TYPE CONVERSION

   In more detail, an input conversion specification consists of an
initial `%' character followed in sequence by:

   * An optional "flag character" `*', which says to ignore the text
     read for this specification.  When `scanf' finds a conversion
     specification that uses this flag, it reads input as directed by
     the rest of the conversion specification, but it discards this
     input, does not use a pointer argument, and does not increment the
     count of successful assignments.

   * An optional flag character `a' (valid with string conversions only)
     which requests allocation of a buffer long enough to store the
     string in.  (This is a GNU extension.)  See Dynamic String Input.

   * An optional decimal integer that specifies the "maximum field
     width".  Reading of characters from the input stream stops either
     when this maximum is reached or when a non-matching character is
     found, whichever happens first.  Most conversions discard initial
     whitespace characters (those that don't are explicitly
     documented), and these discarded characters don't count towards
     the maximum field width.  String input conversions store a null
     character to mark the end of the input; the maximum field width
     does not include this terminator.

   * An optional "type modifier character".  For example, you can
     specify a type modifier of `l' with integer conversions such as
     `%d' to specify that the argument is a pointer to a `long int'
     rather than a pointer to an `int'.

   * A character that specifies the conversion to be applied.

   The exact options that are permitted and how they are interpreted
vary between the different conversion specifiers.  See the descriptions
of the individual conversions for information about the particular
options that they allow.

   With the `-Wformat' option, the GNU C compiler checks calls to
`scanf' and related functions.  It examines the format string and
verifies that the correct number and types of arguments are supplied.
There is also a GNU C syntax to tell the compiler that a function you
write uses a `scanf'-style format string.  See Declaring Attributes of Functions (gcc.info),
for more information.

Table of Input Conversions
--------------------------

   Here is a table that summarizes the various conversion
specifications:

`%d'
     Matches an optionally signed integer written in decimal.  See
     Numeric Input Conversions.

`%i'
     Matches an optionally signed integer in any of the formats that
     the C language defines for specifying an integer constant.  See
     Numeric Input Conversions.

`%o'
     Matches an unsigned integer written in octal radix.  See Numeric Input Conversions.

`%u'
     Matches an unsigned integer written in decimal radix.  See
     Numeric Input Conversions.

`%x', `%X'
     Matches an unsigned integer written in hexadecimal radix.  See
     Numeric Input Conversions.

`%e', `%f', `%g', `%E', `%G'
     Matches an optionally signed floating-point number.  See Numeric Input Conversions.

`%s'
     Matches a string containing only non-whitespace characters.  See
     String Input Conversions.

`%['
     Matches a string of characters that belong to a specified set.
     See String Input Conversions.

`%c'
     Matches a string of one or more characters; the number of
     characters read is controlled by the maximum field width given for
     the conversion.  See String Input Conversions.

`%p'
     Matches a pointer value in the same implementation-defined format
     used by the `%p' output conversion for `printf'.  See Other Input Conversions.

`%n'
     This conversion doesn't read any characters; it records the number
     of characters read so far by this call.  See Other Input Conversions.

`%%'
     This matches a literal `%' character in the input stream.  No
     corresponding argument is used.  See Other Input Conversions.

   If the syntax of a conversion specification is invalid, the behavior
is undefined.  If there aren't enough function arguments provided to
supply addresses for all the conversion specifications in the template
strings that perform assignments, or if the arguments are not of the
correct types, the behavior is also undefined.  On the other hand, extra
arguments are simply ignored.

Numeric Input Conversions
-------------------------

   This section describes the `scanf' conversions for reading numeric
values.

   The `%d' conversion matches an optionally signed integer in decimal
radix.  The syntax that is recognized is the same as that for the
`strtol' function (see Parsing of Integers.) with the value `10'
for the BASE argument.

   The `%i' conversion matches an optionally signed integer in any of
the formats that the C language defines for specifying an integer
constant.  The syntax that is recognized is the same as that for the
`strtol' function (see Parsing of Integers.) with the value `0' for
the BASE argument.  (You can print integers in this syntax with
`printf' by using the `#' flag character with the `%x', `%o', or `%d'
conversion.  See Integer Conversions.)

   For example, any of the strings `10', `0xa', or `012' could be read
in as integers under the `%i' conversion.  Each of these specifies a
number with decimal value `10'.

   The `%o', `%u', and `%x' conversions match unsigned integers in
octal, decimal, and hexadecimal radices, respectively.  The syntax that
is recognized is the same as that for the `strtoul' function (see
Parsing of Integers.) with the appropriate value (`8', `10', or `16')
for the BASE argument.

   The `%X' conversion is identical to the `%x' conversion.  They both
permit either uppercase or lowercase letters to be used as digits.

   The default type of the corresponding argument for the `%d' and `%i'
conversions is `int *', and `unsigned int *' for the other integer
conversions.  You can use the following type modifiers to specify other
sizes of integer:

`h'
     Specifies that the argument is a `short int *' or `unsigned short
     int *'.

`l'
     Specifies that the argument is a `long int *' or `unsigned long
     int *'.  Two `l' characters is like the `L' modifier, below.

`ll'
`L'
`q'
     Specifies that the argument is a `long long int *' or `unsigned
     long long int *'.  (The `long long' type is an extension supported
     by the GNU C compiler.  For systems that don't provide extra-long
     integers, this is the same as `long int'.)

     The `q' modifier is another name for the same thing, which comes
     from 4.4 BSD; a `long long int' is sometimes called a "quad" `int'.

   All of the `%e', `%f', `%g', `%E', and `%G' input conversions are
interchangeable.  They all match an optionally signed floating point
number, in the same syntax as for the `strtod' function (see Parsing of Floats.).

   For the floating-point input conversions, the default argument type
is `float *'.  (This is different from the corresponding output
conversions, where the default type is `double'; remember that `float'
arguments to `printf' are converted to `double' by the default argument
promotions, but `float *' arguments are not promoted to `double *'.)
You can specify other sizes of float using these type modifiers:

`l'
     Specifies that the argument is of type `double *'.

`L'
     Specifies that the argument is of type `long double *'.

   For all the above number parsing formats there is an additional
optional flag `''.  When this flag is given the `scanf' function
expects the number represented in the input string to be formatted
according to the grouping rules of the currently selected locale (see
General Numeric.).

   If the `"C"' or `"POSIX"' locale is selected there is no difference.
But for a locale which specifies values for the appropriate fields in
the locale the input must have the correct form in the input.
Otherwise the longest prefix with a correct form is processed.

String Input Conversions
------------------------

   This section describes the `scanf' input conversions for reading
string and character values: `%s', `%[', and `%c'.

   You have two options for how to receive the input from these
conversions:

   * Provide a buffer to store it in.  This is the default.  You should
     provide an argument of type `char *'.

     *Warning:* To make a robust program, you must make sure that the
     input (plus its terminating null) cannot possibly exceed the size
     of the buffer you provide.  In general, the only way to do this is
     to specify a maximum field width one less than the buffer size.
     *If you provide the buffer, always specify a maximum field width
     to prevent overflow.*

   * Ask `scanf' to allocate a big enough buffer, by specifying the `a'
     flag character.  This is a GNU extension.  You should provide an
     argument of type `char **' for the buffer address to be stored in.
     See Dynamic String Input.

   The `%c' conversion is the simplest: it matches a fixed number of
characters, always.  The maximum field with says how many characters to
read; if you don't specify the maximum, the default is 1.  This
conversion doesn't append a null character to the end of the text it
reads.  It also does not skip over initial whitespace characters.  It
reads precisely the next N characters, and fails if it cannot get that
many.  Since there is always a maximum field width with `%c' (whether
specified, or 1 by default), you can always prevent overflow by making
the buffer long enough.

   The `%s' conversion matches a string of non-whitespace characters.
It skips and discards initial whitespace, but stops when it encounters
more whitespace after having read something.  It stores a null character
at the end of the text that it reads.

   For example, reading the input:

      hello, world

with the conversion `%10c' produces `" hello, wo"', but reading the
same input with the conversion `%10s' produces `"hello,"'.

   *Warning:* If you do not specify a field width for `%s', then the
number of characters read is limited only by where the next whitespace
character appears.  This almost certainly means that invalid input can
make your program crash--which is a bug.

   To read in characters that belong to an arbitrary set of your choice,
use the `%[' conversion.  You specify the set between the `[' character
and a following `]' character, using the same syntax used in regular
expressions.  As special cases:

   * A literal `]' character can be specified as the first character of
     the set.

   * An embedded `-' character (that is, one that is not the first or
     last character of the set) is used to specify a range of
     characters.

   * If a caret character `^' immediately follows the initial `[', then
     the set of allowed input characters is the everything *except* the
     characters listed.

   The `%[' conversion does not skip over initial whitespace characters.

   Here are some examples of `%[' conversions and what they mean:

`%25[1234567890]'
     Matches a string of up to 25 digits.

`%25[][]'
     Matches a string of up to 25 square brackets.

`%25[^ \f\n\r\t\v]'
     Matches a string up to 25 characters long that doesn't contain any
     of the standard whitespace characters.  This is slightly different
     from `%s', because if the input begins with a whitespace character,
     `%[' reports a matching failure while `%s' simply discards the
     initial whitespace.

`%25[a-z]'
     Matches up to 25 lowercase characters.

   One more reminder: the `%s' and `%[' conversions are *dangerous* if
you don't specify a maximum width or use the `a' flag, because input
too long would overflow whatever buffer you have provided for it.  No
matter how long your buffer is, a user could supply input that is
longer.  A well-written program reports invalid input with a
comprehensible error message, not with a crash.

Dynamically Allocating String Conversions
-----------------------------------------

   A GNU extension to formatted input lets you safely read a string
with no maximum size.  Using this feature, you don't supply a buffer;
instead, `scanf' allocates a buffer big enough to hold the data and
gives you its address.  To use this feature, write `a' as a flag
character, as in `%as' or `%a[0-9a-z]'.

   The pointer argument you supply for where to store the input should
have type `char **'.  The `scanf' function allocates a buffer and
stores its address in the word that the argument points to.  You should
free the buffer with `free' when you no longer need it.

   Here is an example of using the `a' flag with the `%[...]'
conversion specification to read a "variable assignment" of the form
`VARIABLE = VALUE'.

     {
       char *variable, *value;

       if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n",
                      &variable, &value))
         {
           invalid_input_error ();
           return 0;
         }

       ...
     }

Other Input Conversions
-----------------------

   This section describes the miscellaneous input conversions.

   The `%p' conversion is used to read a pointer value.  It recognizes
the same syntax as is used by the `%p' output conversion for `printf'
(see Other Output Conversions.); that is, a hexadecimal number just
as the `%x' conversion accepts.  The corresponding argument should be
of type `void **'; that is, the address of a place to store a pointer.

   The resulting pointer value is not guaranteed to be valid if it was
not originally written during the same program execution that reads it
in.

   The `%n' conversion produces the number of characters read so far by
this call.  The corresponding argument should be of type `int *'.  This
conversion works in the same way as the `%n' conversion for `printf';
see Other Output Conversions, for an example.

   The `%n' conversion is the only mechanism for determining the
success of literal matches or conversions with suppressed assignments.
If the `%n' follows the locus of a matching failure, then no value is
stored for it since `scanf' returns before processing the `%n'.  If you
store `-1' in that argument slot before calling `scanf', the presence
of `-1' after `scanf' indicates an error occurred before the `%n' was
reached.

   Finally, the `%%' conversion matches a literal `%' character in the
input stream, without using an argument.  This conversion does not
permit any flags, field width, or type modifier to be specified.