This is Info file libc.info, produced by Makeinfo version 1.68 from the
input file libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.09 DRAFT, last updated 28 Aug 1999, of `The GNU C
Library Reference Manual', for Version 2.2 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.


File: libc.info,  Node: Line Input,  Next: Unreading,  Prev: Character Input,  Up: I/O on Streams

Line-Oriented Input
===================

   Since many programs interpret input on the basis of lines, it's
convenient to have functions to read a line of text from a stream.

   Standard C has functions to do this, but they aren't very safe: null
characters and even (for `gets') long lines can confuse them.  So the
GNU library provides the nonstandard `getline' function that makes it
easy to read lines reliably.

   Another GNU extension, `getdelim', generalizes `getline'.  It reads
a delimited record, defined as everything through the next occurrence
of a specified delimiter character.

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

 - Function: ssize_t getline (char **LINEPTR, size_t *N, FILE *STREAM)
     This function reads an entire line from STREAM, storing the text
     (including the newline and a terminating null character) in a
     buffer and storing the buffer address in `*LINEPTR'.

     Before calling `getline', you should place in `*LINEPTR' the
     address of a buffer `*N' bytes long, allocated with `malloc'.  If
     this buffer is long enough to hold the line, `getline' stores the
     line in this buffer.  Otherwise, `getline' makes the buffer bigger
     using `realloc', storing the new buffer address back in `*LINEPTR'
     and the increased size back in `*N'.  *Note Unconstrained
     Allocation::.

     If you set `*LINEPTR' to a null pointer, and `*N' to zero, before
     the call, then `getline' allocates the initial buffer for you by
     calling `malloc'.

     In either case, when `getline' returns,  `*LINEPTR' is a `char *'
     which points to the text of the line.

     When `getline' is successful, it returns the number of characters
     read (including the newline, but not including the terminating
     null).  This value enables you to distinguish null characters that
     are part of the line from the null character inserted as a
     terminator.

     This function is a GNU extension, but it is the recommended way to
     read lines from a stream.  The alternative standard functions are
     unreliable.

     If an error occurs or end of file is reached, `getline' returns
     `-1'.

 - Function: ssize_t getdelim (char **LINEPTR, size_t *N, int
          DELIMITER, FILE *STREAM)
     This function is like `getline' except that the character which
     tells it to stop reading is not necessarily newline.  The argument
     DELIMITER specifies the delimiter character; `getdelim' keeps
     reading until it sees that character (or end of file).

     The text is stored in LINEPTR, including the delimiter character
     and a terminating null.  Like `getline', `getdelim' makes LINEPTR
     bigger if it isn't big enough.

     `getline' is in fact implemented in terms of `getdelim', just like
     this:

          ssize_t
          getline (char **lineptr, size_t *n, FILE *stream)
          {
            return getdelim (lineptr, n, '\n', stream);
          }

 - Function: char * fgets (char *S, int COUNT, FILE *STREAM)
     The `fgets' function reads characters from the stream STREAM up to
     and including a newline character and stores them in the string S,
     adding a null character to mark the end of the string.  You must
     supply COUNT characters worth of space in S, but the number of
     characters read is at most COUNT - 1.  The extra character space
     is used to hold the null character at the end of the string.

     If the system is already at end of file when you call `fgets', then
     the contents of the array S are unchanged and a null pointer is
     returned.  A null pointer is also returned if a read error occurs.
     Otherwise, the return value is the pointer S.

     *Warning:*  If the input data has a null character, you can't tell.
     So don't use `fgets' unless you know the data cannot contain a
     null.  Don't use it to read files edited by the user because, if
     the user inserts a null character, you should either handle it
     properly or print a clear error message.  We recommend using
     `getline' instead of `fgets'.

 - Deprecated function: char * gets (char *S)
     The function `gets' reads characters from the stream `stdin' up to
     the next newline character, and stores them in the string S.  The
     newline character is discarded (note that this differs from the
     behavior of `fgets', which copies the newline character into the
     string).  If `gets' encounters a read error or end-of-file, it
     returns a null pointer; otherwise it returns S.

     *Warning:* The `gets' function is *very dangerous* because it
     provides no protection against overflowing the string S.  The GNU
     library includes it for compatibility only.  You should *always*
     use `fgets' or `getline' instead.  To remind you of this, the
     linker (if using GNU `ld') will issue a warning whenever you use
     `gets'.


File: libc.info,  Node: Unreading,  Next: Block Input/Output,  Prev: Line Input,  Up: I/O on Streams

Unreading
=========

   In parser programs it is often useful to examine the next character
in the input stream without removing it from the stream.  This is called
"peeking ahead" at the input because your program gets a glimpse of the
input it will read next.

   Using stream I/O, you can peek ahead at input by first reading it and
then "unreading" it (also called  "pushing it back" on the stream).
Unreading a character makes it available to be input again from the
stream, by  the next call to `fgetc' or other input function on that
stream.

* Menu:

* Unreading Idea::              An explanation of unreading with pictures.
* How Unread::                  How to call `ungetc' to do unreading.


File: libc.info,  Node: Unreading Idea,  Next: How Unread,  Up: Unreading

What Unreading Means
--------------------

   Here is a pictorial explanation of unreading.  Suppose you have a
stream reading a file that contains just six characters, the letters
`foobar'.  Suppose you have read three characters so far.  The
situation looks like this:

     f  o  o  b  a  r
              ^

so the next input character will be `b'.

   If instead of reading `b' you unread the letter `o', you get a
situation like this:

     f  o  o  b  a  r
              |
           o--
           ^

so that the next input characters will be `o' and `b'.

   If you unread `9' instead of `o', you get this situation:

     f  o  o  b  a  r
              |
           9--
           ^

so that the next input characters will be `9' and `b'.


File: libc.info,  Node: How Unread,  Prev: Unreading Idea,  Up: Unreading

Using `ungetc' To Do Unreading
------------------------------

   The function to unread a character is called `ungetc', because it
reverses the action of `getc'.

 - Function: int ungetc (int C, FILE *STREAM)
     The `ungetc' function pushes back the character C onto the input
     stream STREAM.  So the next input from STREAM will read C before
     anything else.

     If C is `EOF', `ungetc' does nothing and just returns `EOF'.  This
     lets you call `ungetc' with the return value of `getc' without
     needing to check for an error from `getc'.

     The character that you push back doesn't have to be the same as
     the last character that was actually read from the stream.  In
     fact, it isn't necessary to actually read any characters from the
     stream before unreading them with `ungetc'!  But that is a strange
     way to write a program; usually `ungetc' is used only to unread a
     character that was just read from the same stream.

     The GNU C library only supports one character of pushback--in other
     words, it does not work to call `ungetc' twice without doing input
     in between.  Other systems might let you push back multiple
     characters; then reading from the stream retrieves the characters
     in the reverse order that they were pushed.

     Pushing back characters doesn't alter the file; only the internal
     buffering for the stream is affected.  If a file positioning
     function (such as `fseek', `fseeko' or `rewind'; *note File
     Positioning::.) is called, any pending pushed-back characters are
     discarded.

     Unreading a character on a stream that is at end of file clears the
     end-of-file indicator for the stream, because it makes the
     character of input available.  After you read that character,
     trying to read again will encounter end of file.

   Here is an example showing the use of `getc' and `ungetc' to skip
over whitespace characters.  When this function reaches a
non-whitespace character, it unreads that character to be seen again on
the next read operation on the stream.

     #include <stdio.h>
     #include <ctype.h>
     
     void
     skip_whitespace (FILE *stream)
     {
       int c;
       do
         /* No need to check for `EOF' because it is not
            `isspace', and `ungetc' ignores `EOF'.  */
         c = getc (stream);
       while (isspace (c));
       ungetc (c, stream);
     }


File: libc.info,  Node: Block Input/Output,  Next: Formatted Output,  Prev: Unreading,  Up: I/O on Streams

Block Input/Output
==================

   This section describes how to do input and output operations on
blocks of data.  You can use these functions to read and write binary
data, as well as to read and write text in fixed-size blocks instead of
by characters or lines.

   Binary files are typically used to read and write blocks of data in
the same format as is used to represent the data in a running program.
In other words, arbitrary blocks of memory--not just character or string
objects--can be written to a binary file, and meaningfully read in
again by the same program.

   Storing data in binary form is often considerably more efficient than
using the formatted I/O functions.  Also, for floating-point numbers,
the binary form avoids possible loss of precision in the conversion
process.  On the other hand, binary files can't be examined or modified
easily using many standard file utilities (such as text editors), and
are not portable between different implementations of the language, or
different kinds of computers.

   These functions are declared in `stdio.h'.

 - Function: size_t fread (void *DATA, size_t SIZE, size_t COUNT, FILE
          *STREAM)
     This function reads up to COUNT objects of size SIZE into the
     array DATA, from the stream STREAM.  It returns the number of
     objects actually read, which might be less than COUNT if a read
     error occurs or the end of the file is reached.  This function
     returns a value of zero (and doesn't read anything) if either SIZE
     or COUNT is zero.

     If `fread' encounters end of file in the middle of an object, it
     returns the number of complete objects read, and discards the
     partial object.  Therefore, the stream remains at the actual end
     of the file.

 - Function: size_t fwrite (const void *DATA, size_t SIZE, size_t
          COUNT, FILE *STREAM)
     This function writes up to COUNT objects of size SIZE from the
     array DATA, to the stream STREAM.  The return value is normally
     COUNT, if the call succeeds.  Any other value indicates some sort
     of error, such as running out of space.


File: libc.info,  Node: Formatted Output,  Next: Customizing Printf,  Prev: Block Input/Output,  Up: I/O on Streams

Formatted Output
================

   The functions described in this section (`printf' and related
functions) provide a convenient way to perform formatted output.  You
call `printf' with a "format string" or "template string" that
specifies how to format the values of the remaining arguments.

   Unless your program is a filter that specifically performs line- or
character-oriented processing, using `printf' or one of the other
related functions described in this section is usually the easiest and
most concise way to perform output.  These functions are especially
useful for printing error messages, tables of data, and the like.

* Menu:

* Formatted Output Basics::     Some examples to get you started.
* Output Conversion Syntax::    General syntax of conversion
                                 specifications.
* Table of Output Conversions:: Summary of output conversions and
                                 what they do.
* Integer Conversions::         Details about formatting of integers.
* Floating-Point Conversions::  Details about formatting of
                                 floating-point numbers.
* Other Output Conversions::    Details about formatting of strings,
                                 characters, pointers, and the like.
* Formatted Output Functions::  Descriptions of the actual functions.
* Dynamic Output::		Functions that allocate memory for the output.
* Variable Arguments Output::   `vprintf' and friends.
* Parsing a Template String::   What kinds of args does a given template
                                 call for?
* Example of Parsing::          Sample program using `parse_printf_format'.


File: libc.info,  Node: Formatted Output Basics,  Next: Output Conversion Syntax,  Up: Formatted Output

Formatted Output Basics
-----------------------

   The `printf' function can be used to print any number of arguments.
The template string argument you supply in a call provides information
not only about the number of additional arguments, but also about their
types and what style should be used for printing them.

   Ordinary characters in the template string are simply written to the
output stream as-is, while "conversion specifications" introduced by a
`%' character in the template cause subsequent arguments to be
formatted and written to the output stream.  For example,

     int pct = 37;
     char filename[] = "foo.txt";
     printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
             filename, pct);

produces output like

     Processing of `foo.txt' is 37% finished.
     Please be patient.

   This example shows the use of the `%d' conversion to specify that an
`int' argument should be printed in decimal notation, the `%s'
conversion to specify printing of a string argument, and the `%%'
conversion to print a literal `%' character.

   There are also conversions for printing an integer argument as an
unsigned value in octal, decimal, or hexadecimal radix (`%o', `%u', or
`%x', respectively); or as a character value (`%c').

   Floating-point numbers can be printed in normal, fixed-point notation
using the `%f' conversion or in exponential notation using the `%e'
conversion.  The `%g' conversion uses either `%e' or `%f' format,
depending on what is more appropriate for the magnitude of the
particular number.

   You can control formatting more precisely by writing "modifiers"
between the `%' and the character that indicates which conversion to
apply.  These slightly alter the ordinary behavior of the conversion.
For example, most conversion specifications permit you to specify a
minimum field width and a flag indicating whether you want the result
left- or right-justified within the field.

   The specific flags and modifiers that are permitted and their
interpretation vary depending on the particular conversion.  They're all
described in more detail in the following sections.  Don't worry if this
all seems excessively complicated at first; you can almost always get
reasonable free-format output without using any of the modifiers at all.
The modifiers are mostly used to make the output look "prettier" in
tables.


File: libc.info,  Node: Output Conversion Syntax,  Next: Table of Output Conversions,  Prev: Formatted Output Basics,  Up: Formatted Output

Output Conversion Syntax
------------------------

   This section provides details about the precise syntax of conversion
specifications that can appear in a `printf' template string.

   Characters in the template string that are not part of a conversion
specification are printed as-is to the output stream.  Multibyte
character sequences (*note Character Set Handling::.) are permitted in a
template string.

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

     % [ PARAM-NO $] FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION

   For example, in the conversion specifier `%-10.8ld', the `-' is a
flag, `10' specifies the field width, the precision is `8', the letter
`l' is a type modifier, and `d' specifies the conversion style.  (This
particular type specifier says to print a `long int' argument in
decimal notation, with a minimum of 8 digits left-justified in a field
at least 10 characters wide.)

   In more detail, output conversion specifications consist of an
initial `%' character followed in sequence by:

   * An optional specification of the parameter used for this format.
     Normally the parameters to the `printf' function are assigned to
     the formats in the order of appearance in the format string.  But
     in some situations (such as message translation) this is not
     desirable and this extension allows an explicit parameter to be
     specified.

     The PARAM-NO part of the format must be an integer in the range of
     1 to the maximum number of arguments present to the function call.
     Some implementations limit this number to a certainly upper
     bound.  The exact limit can be retrieved by the following constant.

      - Macro: NL_ARGMAX
          The value of `ARGMAX' is the maximum value allowed for the
          specification of an positional parameter in a `printf' call.
          The actual value in effect at runtime can be retrieved by
          using `sysconf' using the `_SC_NL_ARGMAX' parameter *note
          Sysconf Definition::..

          Some system have a quite low limit such as 9 for System V
          systems.  The GNU C library has no real limit.

     If any of the formats has a specification for the parameter
     position all of them in the format string shall have one.
     Otherwise the behaviour is undefined.

   * Zero or more "flag characters" that modify the normal behavior of
     the conversion specification.

   * An optional decimal integer specifying the "minimum field width".
     If the normal conversion produces fewer characters than this, the
     field is padded with spaces to the specified width.  This is a
     *minimum* value; if the normal conversion produces more characters
     than this, the field is *not* truncated.  Normally, the output is
     right-justified within the field.

     You can also specify a field width of `*'.  This means that the
     next argument in the argument list (before the actual value to be
     printed) is used as the field width.  The value must be an `int'.
     If the value is negative, this means to set the `-' flag (see
     below) and to use the absolute value as the field width.

   * An optional "precision" to specify the number of digits to be
     written for the numeric conversions.  If the precision is
     specified, it consists of a period (`.') followed optionally by a
     decimal integer (which defaults to zero if omitted).

     You can also specify a precision of `*'.  This means that the next
     argument in the argument list (before the actual value to be
     printed) is used as the precision.  The value must be an `int',
     and is ignored if it is negative.  If you specify `*' for both the
     field width and precision, the field width argument precedes the
     precision argument.  Other C library versions may not recognize
     this syntax.

   * An optional "type modifier character", which is used to specify the
     data type of the corresponding argument if it differs from the
     default type.  (For example, the integer conversions assume a type
     of `int', but you can specify `h', `l', or `L' for other integer
     types.)

   * 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 use.

   With the `-Wformat' option, the GNU C compiler checks calls to
`printf' 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 `printf'-style format string.  *Note Declaring Attributes
of Functions: (gcc.info)Function Attributes, for more information.


File: libc.info,  Node: Table of Output Conversions,  Next: Integer Conversions,  Prev: Output Conversion Syntax,  Up: Formatted Output

Table of Output Conversions
---------------------------

   Here is a table summarizing what all the different conversions do:

`%d', `%i'
     Print an integer as a signed decimal number.  *Note Integer
     Conversions::, for details.  `%d' and `%i' are synonymous for
     output, but are different when used with `scanf' for input (*note
     Table of Input Conversions::.).

`%o'
     Print an integer as an unsigned octal number.  *Note Integer
     Conversions::, for details.

`%u'
     Print an integer as an unsigned decimal number.  *Note Integer
     Conversions::, for details.

`%x', `%X'
     Print an integer as an unsigned hexadecimal number.  `%x' uses
     lower-case letters and `%X' uses upper-case.  *Note Integer
     Conversions::, for details.

`%f'
     Print a floating-point number in normal (fixed-point) notation.
     *Note Floating-Point Conversions::, for details.

`%e', `%E'
     Print a floating-point number in exponential notation.  `%e' uses
     lower-case letters and `%E' uses upper-case.  *Note Floating-Point
     Conversions::, for details.

`%g', `%G'
     Print a floating-point number in either normal or exponential
     notation, whichever is more appropriate for its magnitude.  `%g'
     uses lower-case letters and `%G' uses upper-case.  *Note
     Floating-Point Conversions::, for details.

`%a', `%A'
     Print a floating-point number in a hexadecimal fractional notation
     which the exponent to base 2 represented in decimal digits.  `%a'
     uses lower-case letters and `%A' uses upper-case.  *Note
     Floating-Point Conversions::, for details.

`%c'
     Print a single character.  *Note Other Output Conversions::.

`%s'
     Print a string.  *Note Other Output Conversions::.

`%p'
     Print the value of a pointer.  *Note Other Output Conversions::.

`%n'
     Get the number of characters printed so far.  *Note Other Output
     Conversions::.  Note that this conversion specification never
     produces any output.

`%m'
     Print the string corresponding to the value of `errno'.  (This is
     a GNU extension.)  *Note Other Output Conversions::.

`%%'
     Print a literal `%' character.  *Note Other Output Conversions::.

   If the syntax of a conversion specification is invalid, unpredictable
things will happen, so don't do this.  If there aren't enough function
arguments provided to supply values for all the conversion
specifications in the template string, or if the arguments are not of
the correct types, the results are unpredictable.  If you supply more
arguments than conversion specifications, the extra argument values are
simply ignored; this is sometimes useful.


File: libc.info,  Node: Integer Conversions,  Next: Floating-Point Conversions,  Prev: Table of Output Conversions,  Up: Formatted Output

Integer Conversions
-------------------

   This section describes the options for the `%d', `%i', `%o', `%u',
`%x', and `%X' conversion specifications.  These conversions print
integers in various formats.

   The `%d' and `%i' conversion specifications both print an `int'
argument as a signed decimal number; while `%o', `%u', and `%x' print
the argument as an unsigned octal, decimal, or hexadecimal number
(respectively).  The `%X' conversion specification is just like `%x'
except that it uses the characters `ABCDEF' as digits instead of
`abcdef'.

   The following flags are meaningful:

`-'
     Left-justify the result in the field (instead of the normal
     right-justification).

`+'
     For the signed `%d' and `%i' conversions, print a plus sign if the
     value is positive.

` '
     For the signed `%d' and `%i' conversions, if the result doesn't
     start with a plus or minus sign, prefix it with a space character
     instead.  Since the `+' flag ensures that the result includes a
     sign, this flag is ignored if you supply both of them.

`#'
     For the `%o' conversion, this forces the leading digit to be `0',
     as if by increasing the precision.  For `%x' or `%X', this
     prefixes a leading `0x' or `0X' (respectively) to the result.
     This doesn't do anything useful for the `%d', `%i', or `%u'
     conversions.  Using this flag produces output which can be parsed
     by the `strtoul' function (*note Parsing of Integers::.) and
     `scanf' with the `%i' conversion (*note Numeric Input
     Conversions::.).

`''
     Separate the digits into groups as specified by the locale
     specified for the `LC_NUMERIC' category; *note General Numeric::..
     This flag is a GNU extension.

`0'
     Pad the field with zeros instead of spaces.  The zeros are placed
     after any indication of sign or base.  This flag is ignored if the
     `-' flag is also specified, or if a precision is specified.

   If a precision is supplied, it specifies the minimum number of
digits to appear; leading zeros are produced if necessary.  If you
don't specify a precision, the number is printed with as many digits as
it needs.  If you convert a value of zero with an explicit precision of
zero, then no characters at all are produced.

   Without a type modifier, the corresponding argument is treated as an
`int' (for the signed conversions `%i' and `%d') or `unsigned int' (for
the unsigned conversions `%o', `%u', `%x', and `%X').  Recall that
since `printf' and friends are variadic, any `char' and `short'
arguments are automatically converted to `int' by the default argument
promotions.  For arguments of other integer types, you can use these
modifiers:

`hh'
     Specifies that the argument is a `signed char' or `unsigned char',
     as appropriate.  A `char' argument is converted to an `int' or
     `unsigned int' by the default argument promotions anyway, but the
     `h' modifier says to convert it back to a `char' again.

     This modifier was introduced in ISO C99.

`h'
     Specifies that the argument is a `short int' or `unsigned short
     int', as appropriate.  A `short' argument is converted to an `int'
     or `unsigned int' by the default argument promotions anyway, but
     the `h' modifier says to convert it back to a `short' again.

`j'
     Specifies that the argument is a `intmax_t' or `uintmax_t', as
     appropriate.

     This modifier was introduced in ISO C99.

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

`L'
`ll'
`q'
     Specifies that the argument is a `long long int'.  (This type is
     an extension supported by the GNU C compiler.  On systems that
     don't support 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'.

`t'
     Specifies that the argument is a `ptrdiff_t'.

     This modifier was introduced in ISO C99.

`z'
`Z'
     Specifies that the argument is a `size_t'.

     `z' was introduced in ISO C99.  `Z' is a GNU extension predating
     this addition and should not be used in new code.

   Here is an example.  Using the template string:

     "|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"

to print numbers using the different options for the `%d' conversion
gives results like:

     |    0|0    |   +0|+0   |    0|00000|     |   00|0|
     |    1|1    |   +1|+1   |    1|00001|    1|   01|1|
     |   -1|-1   |   -1|-1   |   -1|-0001|   -1|  -01|-1|
     |100000|100000|+100000| 100000|100000|100000|100000|100000|

   In particular, notice what happens in the last case where the number
is too large to fit in the minimum field width specified.

   Here are some more examples showing how unsigned integers print under
various format options, using the template string:

     "|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"

     |    0|    0|    0|    0|    0|  0x0|  0X0|0x00000000|
     |    1|    1|    1|    1|   01|  0x1|  0X1|0x00000001|
     |100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|


File: libc.info,  Node: Floating-Point Conversions,  Next: Other Output Conversions,  Prev: Integer Conversions,  Up: Formatted Output

Floating-Point Conversions
--------------------------

   This section discusses the conversion specifications for
floating-point numbers: the `%f', `%e', `%E', `%g', and `%G'
conversions.

   The `%f' conversion prints its argument in fixed-point notation,
producing output of the form [`-']DDD`.'DDD, where the number of digits
following the decimal point is controlled by the precision you specify.

   The `%e' conversion prints its argument in exponential notation,
producing output of the form [`-']D`.'DDD`e'[`+'|`-']DD.  Again, the
number of digits following the decimal point is controlled by the
precision.  The exponent always contains at least two digits.  The `%E'
conversion is similar but the exponent is marked with the letter `E'
instead of `e'.

   The `%g' and `%G' conversions print the argument in the style of
`%e' or `%E' (respectively) if the exponent would be less than -4 or
greater than or equal to the precision; otherwise they use the `%f'
style.  Trailing zeros are removed from the fractional portion of the
result and a decimal-point character appears only if it is followed by
a digit.

   The `%a' and `%A' conversions are meant for representing
floating-point numbers exactly in textual form so that they can be
exchanged as texts between different programs and/or machines.  The
numbers are represented is the form [`-']`0x'H`.'HHH`p'[`+'|`-']DD.  At
the left of the decimal-point character exactly one digit is print.
This character is only `0' if the number is denormalized.  Otherwise
the value is unspecified; it is implementation dependent how many bits
are used.  The number of hexadecimal digits on the right side of the
decimal-point character is equal to the precision.  If the precision is
zero it is determined to be large enough to provide an exact
representation of the number (or it is large enough to distinguish two
adjacent values if the `FLT_RADIX' is not a power of 2, *note Floating
Point Parameters::.).  For the `%a' conversion lower-case characters
are used to represent the hexadecimal number and the prefix and
exponent sign are printed as `0x' and `p' respectively.  Otherwise
upper-case characters are used and `0X' and `P' are used for the
representation of prefix and exponent string.  The exponent to the base
of two is printed as a decimal number using at least one digit but at
most as many digits as necessary to represent the value exactly.

   If the value to be printed represents infinity or a NaN, the output
is [`-']`inf' or `nan' respectively if the conversion specifier is
`%a', `%e', `%f', or `%g' and it is [`-']`INF' or `NAN' respectively if
the conversion is `%A', `%E', or `%G'.

   The following flags can be used to modify the behavior:

`-'
     Left-justify the result in the field.  Normally the result is
     right-justified.

`+'
     Always include a plus or minus sign in the result.

` '
     If the result doesn't start with a plus or minus sign, prefix it
     with a space instead.  Since the `+' flag ensures that the result
     includes a sign, this flag is ignored if you supply both of them.

`#'
     Specifies that the result should always include a decimal point,
     even if no digits follow it.  For the `%g' and `%G' conversions,
     this also forces trailing zeros after the decimal point to be left
     in place where they would otherwise be removed.

`''
     Separate the digits of the integer part of the result into groups
     as specified by the locale specified for the `LC_NUMERIC' category;
     *note General Numeric::..  This flag is a GNU extension.

`0'
     Pad the field with zeros instead of spaces; the zeros are placed
     after any sign.  This flag is ignored if the `-' flag is also
     specified.

   The precision specifies how many digits follow the decimal-point
character for the `%f', `%e', and `%E' conversions.  For these
conversions, the default precision is `6'.  If the precision is
explicitly `0', this suppresses the decimal point character entirely.
For the `%g' and `%G' conversions, the precision specifies how many
significant digits to print.  Significant digits are the first digit
before the decimal point, and all the digits after it.  If the
precision is `0' or not specified for `%g' or `%G', it is treated like
a value of `1'.  If the value being printed cannot be expressed
accurately in the specified number of digits, the value is rounded to
the nearest number that fits.

   Without a type modifier, the floating-point conversions use an
argument of type `double'.  (By the default argument promotions, any
`float' arguments are automatically converted to `double'.)  The
following type modifier is supported:

`L'
     An uppercase `L' specifies that the argument is a `long double'.

   Here are some examples showing how numbers print using the various
floating-point conversions.  All of the numbers were printed using this
template string:

     "|%13.4a|%13.4f|%13.4e|%13.4g|\n"

   Here is the output:

     |  0x0.0000p+0|       0.0000|   0.0000e+00|            0|
     |  0x1.0000p-1|       0.5000|   5.0000e-01|          0.5|
     |  0x1.0000p+0|       1.0000|   1.0000e+00|            1|
     | -0x1.0000p+0|      -1.0000|  -1.0000e+00|           -1|
     |  0x1.9000p+6|     100.0000|   1.0000e+02|          100|
     |  0x1.f400p+9|    1000.0000|   1.0000e+03|         1000|
     | 0x1.3880p+13|   10000.0000|   1.0000e+04|        1e+04|
     | 0x1.81c8p+13|   12345.0000|   1.2345e+04|    1.234e+04|
     | 0x1.86a0p+16|  100000.0000|   1.0000e+05|        1e+05|
     | 0x1.e240p+16|  123456.0000|   1.2346e+05|    1.235e+05|

   Notice how the `%g' conversion drops trailing zeros.


File: libc.info,  Node: Other Output Conversions,  Next: Formatted Output Functions,  Prev: Floating-Point Conversions,  Up: Formatted Output

Other Output Conversions
------------------------

   This section describes miscellaneous conversions for `printf'.

   The `%c' conversion prints a single character.  The `int' argument
is first converted to an `unsigned char'.  The `-' flag can be used to
specify left-justification in the field, but no other flags are
defined, and no precision or type modifier can be given.  For example:

     printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');

prints `hello'.

   The `%s' conversion prints a string.  The corresponding argument
must be of type `char *' (or `const char *').  A precision can be
specified to indicate the maximum number of characters to write;
otherwise characters in the string up to but not including the
terminating null character are written to the output stream.  The `-'
flag can be used to specify left-justification in the field, but no
other flags or type modifiers are defined for this conversion.  For
example:

     printf ("%3s%-6s", "no", "where");

prints ` nowhere '.

   If you accidentally pass a null pointer as the argument for a `%s'
conversion, the GNU library prints it as `(null)'.  We think this is
more useful than crashing.  But it's not good practice to pass a null
argument intentionally.

   The `%m' conversion prints the string corresponding to the error
code in `errno'.  *Note Error Messages::.  Thus:

     fprintf (stderr, "can't open `%s': %m\n", filename);

is equivalent to:

     fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));

The `%m' conversion is a GNU C library extension.

   The `%p' conversion prints a pointer value.  The corresponding
argument must be of type `void *'.  In practice, you can use any type
of pointer.

   In the GNU system, non-null pointers are printed as unsigned
integers, as if a `%#x' conversion were used.  Null pointers print as
`(nil)'.  (Pointers might print differently in other systems.)

   For example:

     printf ("%p", "testing");

prints `0x' followed by a hexadecimal number--the address of the string
constant `"testing"'.  It does not print the word `testing'.

   You can supply the `-' flag with the `%p' conversion to specify
left-justification, but no other flags, precision, or type modifiers
are defined.

   The `%n' conversion is unlike any of the other output conversions.
It uses an argument which must be a pointer to an `int', but instead of
printing anything it stores the number of characters printed so far by
this call at that location.  The `h' and `l' type modifiers are
permitted to specify that the argument is of type `short int *' or
`long int *' instead of `int *', but no flags, field width, or
precision are permitted.

   For example,

     int nchar;
     printf ("%d %s%n\n", 3, "bears", &nchar);

prints:

     3 bears

and sets `nchar' to `7', because `3 bears' is seven characters.

   The `%%' conversion prints a literal `%' character.  This conversion
doesn't use an argument, and no flags, field width, precision, or type
modifiers are permitted.


File: libc.info,  Node: Formatted Output Functions,  Next: Dynamic Output,  Prev: Other Output Conversions,  Up: Formatted Output

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.
     *Note 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 which would be
     generated for the given input, excluding the trailing null.  If
     this value is greater or equal to SIZE, not all characters from
     the result have been stored in S.  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);
            int nchars;

          /* Try to print in the allocated space. */
            nchars = snprintf (buffer, size, "value of %s is %s",
                               name, value);

          if (nchars >= size)
              {
                /* Reallocate buffer now that we know
                   how much space is needed. */
                buffer = (char *) xrealloc (buffer, nchars + 1);
          
                /* Try again. */
                snprintf (buffer, size, "value of %s is %s",
                          name, value);
              }
            /* The last call worked, return the string. */
            return buffer;
          }

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

     *Attention:* In the GNU C library version 2.0 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.  This change was necessary with the
     adoption of snprintf by ISO C99.


File: libc.info,  Node: Dynamic Output,  Next: Variable Arguments Output,  Prev: Formatted Output Functions,  Up: Formatted Output

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'; *note 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.  *Note Obstacks::.

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


File: libc.info,  Node: Variable Arguments Output,  Next: Parsing a Template String,  Prev: Dynamic Output,  Up: Formatted Output

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...)

*Note Macros with Variable Numbers of Arguments: (gcc.info)Macro
Varargs, 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' (*note 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 (*note 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, template);
       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'; *note Formatted Input::.); the format
string appears as the first argument; and the arguments to satisfy the
format begin with the second.  *Note Declaring Attributes of Functions:
(gcc.info)Function Attributes, for more information.

