This is libc.info, produced by makeinfo version 4.3 from 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.10, last updated 2001-07-06, of `The GNU C Library
Reference Manual', for Version 2.2.x.

   Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002
Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Free Software Needs Free Documentation" and
"GNU Lesser General Public License", the Front-Cover texts being (a)
(see below), and with the Back-Cover Texts being (b) (see below).  A
copy of the license is included in the section entitled "GNU Free
Documentation License".

   (a) The FSF's Front-Cover Text is:

   A GNU Manual

   (b) The FSF's Back-Cover Text is:

   You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.


File: libc.info,  Node: Streams and Threads,  Next: Streams and I18N,  Prev: Closing Streams,  Up: I/O on Streams

Streams and Threads
===================

   Streams can be used in multi-threaded applications in the same way
they are used in single-threaded applications.  But the programmer must
be aware of a the possible complications.  It is important to know about
these also if the program one writes never use threads since the design
and implementation of many stream functions is heavily influenced by the
requirements added by multi-threaded programming.

   The POSIX standard requires that by default the stream operations are
atomic.  I.e., issuing two stream operations for the same stream in two
threads at the same time will cause the operations to be executed as if
they were issued sequentially.  The buffer operations performed while
reading or writing are protected from other uses of the same stream.  To
do this each stream has an internal lock object which has to be
(implicitly) acquired before any work can be done.

   But there are situations where this is not enough and there are also
situations where this is not wanted.  The implicit locking is not enough
if the program requires more than one stream function call to happen
atomically.  One example would be if an output line a program wants to
generate is created by several function calls.  The functions by
themselves would ensure only atomicity of their own operation, but not
atomicity over all the function calls.  For this it is necessary to
perform the stream locking in the application code.

 - Function: void flockfile (FILE *STREAM)
     The `flockfile' function acquires the internal locking object
     associated with the stream STREAM.  This ensures that no other
     thread can explicitly through `flockfile'/`ftrylockfile' or
     implicit through a call of a stream function lock the stream.  The
     thread will block until the lock is acquired.  An explicit call to
     `funlockfile' has to be used to release the lock.

 - Function: int ftrylockfile (FILE *STREAM)
     The `ftrylockfile' function tries to acquire the internal locking
     object associated with the stream STREAM just like `flockfile'.
     But unlike `flockfile' this function does not block if the lock is
     not available.  `ftrylockfile' returns zero if the lock was
     successfully acquired.  Otherwise the stream is locked by another
     thread.

 - Function: void funlockfile (FILE *STREAM)
     The `funlockfile' function releases the internal locking object of
     the stream STREAM. The stream must have been locked before by a
     call to `flockfile' or a successful call of `ftrylockfile'.  The
     implicit locking performed by the stream operations do not count.
     The `funlockfile' function does not return an error status and the
     behavior of a call for a stream which is not locked by the current
     thread is undefined.

   The following example shows how the functions above can be used to
generate an output line atomically even in multi-threaded applications
(yes, the same job could be done with one `fprintf' call but it is
sometimes not possible):

     FILE *fp;
     {
        ...
        flockfile (fp);
        fputs ("This is test number ", fp);
        fprintf (fp, "%d\n", test);
        funlockfile (fp)
     }

   Without the explicit locking it would be possible for another thread
to use the stream FP after the `fputs' call return and before `fprintf'
was called with the result that the number does not follow the word
`number'.

   From this description it might already be clear that the locking
objects in streams are no simple mutexes.  Since locking the same
stream twice in the same thread is allowed the locking objects must be
equivalent to recursive mutexes.  These mutexes keep track of the owner
and the number of times the lock is acquired.  The same number of
`funlockfile' calls by the same threads is necessary to unlock the
stream completely.  For instance:

     void
     foo (FILE *fp)
     {
       ftrylockfile (fp);
       fputs ("in foo\n", fp);
       /* This is very wrong!!!  */
       funlockfile (fp);
     }

   It is important here that the `funlockfile' function is only called
if the `ftrylockfile' function succeeded in locking the stream.  It is
therefore always wrong to ignore the result of `ftrylockfile'.  And it
makes no sense since otherwise one would use `flockfile'.  The result
of code like that above is that either `funlockfile' tries to free a
stream that hasn't been locked by the current thread or it frees the
stream prematurely.  The code should look like this:

     void
     foo (FILE *fp)
     {
       if (ftrylockfile (fp) == 0)
         {
           fputs ("in foo\n", fp);
           funlockfile (fp);
         }
     }

   Now that we covered why it is necessary to have these locking it is
necessary to talk about situations when locking is unwanted and what can
be done.  The locking operations (explicit or implicit) don't come for
free.  Even if a lock is not taken the cost is not zero.  The operations
which have to be performed require memory operations that are safe in
multi-processor environments.  With the many local caches involved in
such systems this is quite costly.  So it is best to avoid the locking
completely if it is not needed - because the code in question is never
used in a context where two or more threads may use a stream at a time.
This can be determined most of the time for application code; for
library code which can be used in many contexts one should default to be
conservative and use locking.

   There are two basic mechanisms to avoid locking.  The first is to use
the `_unlocked' variants of the stream operations.  The POSIX standard
defines quite a few of those and the GNU library adds a few more.
These variants of the functions behave just like the functions with the
name without the suffix except that they do not lock the stream.  Using
these functions is very desirable since they are potentially much
faster.  This is not only because the locking operation itself is
avoided.  More importantly, functions like `putc' and `getc' are very
simple and traditionally (before the introduction of threads) were
implemented as macros which are very fast if the buffer is not empty.
With the addition of locking requirements these functions are no longer
implemented as macros since they would would expand to too much code.
But these macros are still available with the same functionality under
the new names `putc_unlocked' and `getc_unlocked'.  This possibly huge
difference of speed also suggests the use of the `_unlocked' functions
even if locking is required.  The difference is that the locking then
has to be performed in the program:

     void
     foo (FILE *fp, char *buf)
     {
       flockfile (fp);
       while (*buf != '/')
         putc_unlocked (*buf++, fp);
       funlockfile (fp);
     }

   If in this example the `putc' function would be used and the
explicit locking would be missing the `putc' function would have to
acquire the lock in every call, potentially many times depending on when
the loop terminates.  Writing it the way illustrated above allows the
`putc_unlocked' macro to be used which means no locking and direct
manipulation of the buffer of the stream.

   A second way to avoid locking is by using a non-standard function
which was introduced in Solaris and is available in the GNU C library
as well.

 - Function: int __fsetlocking (FILE *STREAM, int TYPE)
     The `__fsetlocking' function can be used to select whether the
     stream operations will implicitly acquire the locking object of the
     stream STREAM.  By default this is done but it can be disabled and
     reinstated using this function.  There are three values defined
     for the TYPE parameter.

    `FSETLOCKING_INTERNAL'
          The stream `stream' will from now on use the default internal
          locking.  Every stream operation with exception of the
          `_unlocked' variants will implicitly lock the stream.

    `FSETLOCKING_BYCALLER'
          After the `__fsetlocking' function returns the user is
          responsible for locking the stream.  None of the stream
          operations will implicitly do this anymore until the state is
          set back to `FSETLOCKING_INTERNAL'.

    `FSETLOCKING_QUERY'
          `__fsetlocking' only queries the current locking state of the
          stream.  The return value will be `FSETLOCKING_INTERNAL' or
          `FSETLOCKING_BYCALLER' depending on the state.

     The return value of `__fsetlocking' is either
     `FSETLOCKING_INTERNAL' or `FSETLOCKING_BYCALLER' depending on the
     state of the stream before the call.

     This function and the values for the TYPE parameter are declared
     in `stdio_ext.h'.

   This function is especially useful when program code has to be used
which is written without knowledge about the `_unlocked' functions (or
if the programmer was too lazy to use them).


File: libc.info,  Node: Streams and I18N,  Next: Simple Output,  Prev: Streams and Threads,  Up: I/O on Streams

Streams in Internationalized Applications
=========================================

   ISO C90 introduced the new type `wchar_t' to allow handling larger
character sets.  What was missing was a possibility to output strings
of `wchar_t' directly.  One had to convert them into multibyte strings
using `mbstowcs' (there was no `mbsrtowcs' yet) and then use the normal
stream functions.  While this is doable it is very cumbersome since
performing the conversions is not trivial and greatly increases program
complexity and size.

   The Unix standard early on (I think in XPG4.2) introduced two
additional format specifiers for the `printf' and `scanf' families of
functions.  Printing and reading of single wide characters was made
possible using the `%C' specifier and wide character strings can be
handled with `%S'.  These modifiers behave just like `%c' and `%s' only
that they expect the corresponding argument to have the wide character
type and that the wide character and string are transformed into/from
multibyte strings before being used.

   This was a beginning but it is still not good enough.  Not always is
it desirable to use `printf' and `scanf'.  The other, smaller and
faster functions cannot handle wide characters.  Second, it is not
possible to have a format string for `printf' and `scanf' consisting of
wide characters.  The result is that format strings would have to be
generated if they have to contain non-basic characters.

   In the Amendment 1 to ISO C90 a whole new set of functions was added
to solve the problem.  Most of the stream functions got a counterpart
which take a wide character or wide character string instead of a
character or string respectively.  The new functions operate on the
same streams (like `stdout').  This is different from the model of the
C++ runtime library where separate streams for wide and normal I/O are
used.

   Being able to use the same stream for wide and normal operations
comes with a restriction: a stream can be used either for wide
operations or for normal operations.  Once it is decided there is no
way back.  Only a call to `freopen' or `freopen64' can reset the
"orientation".  The orientation can be decided in three ways:

   * If any of the normal character functions is used (this includes the
     `fread' and `fwrite' functions) the stream is marked as not wide
     oriented.

   * If any of the wide character functions is used the stream is
     marked as wide oriented.

   * The `fwide' function can be used to set the orientation either way.

   It is important to never mix the use of wide and not wide operations
on a stream.  There are no diagnostics issued.  The application behavior
will simply be strange or the application will simply crash.  The
`fwide' function can help avoiding this.

 - Function: int fwide (FILE *STREAM, int MODE)
     The `fwide' function can be used to set and query the state of the
     orientation of the stream STREAM.  If the MODE parameter has a
     positive value the streams get wide oriented, for negative values
     narrow oriented.  It is not possible to overwrite previous
     orientations with `fwide'.  I.e., if the stream STREAM was already
     oriented before the call nothing is done.

     If MODE is zero the current orientation state is queried and
     nothing is changed.

     The `fwide' function returns a negative value, zero, or a positive
     value if the stream is narrow, not at all, or wide oriented
     respectively.

     This function was introduced in Amendment 1 to ISO C90 and is
     declared in `wchar.h'.

   It is generally a good idea to orient a stream as early as possible.
This can prevent surprise especially for the standard streams `stdin',
`stdout', and `stderr'.  If some library function in some situations
uses one of these streams and this use orients the stream in a
different way the rest of the application expects it one might end up
with hard to reproduce errors.  Remember that no errors are signal if
the streams are used incorrectly.  Leaving a stream unoriented after
creation is normally only necessary for library functions which create
streams which can be used in different contexts.

   When writing code which uses streams and which can be used in
different contexts it is important to query the orientation of the
stream before using it (unless the rules of the library interface
demand a specific orientation).  The following little, silly function
illustrates this.

     void
     print_f (FILE *fp)
     {
       if (fwide (fp, 0) > 0)
         /* Positive return value means wide orientation.  */
         fputwc (L'f', fp);
       else
         fputc ('f', fp);
     }

   Note that in this case the function `print_f' decides about the
orientation of the stream if it was unoriented before (will not happen
if the advise above is followed).

   The encoding used for the `wchar_t' values is unspecified and the
user must not make any assumptions about it.  For I/O of `wchar_t'
values this means that it is impossible to write these values directly
to the stream.  This is not what follows from the ISO C locale model
either.  What happens instead is that the bytes read from or written to
the underlying media are first converted into the internal encoding
chosen by the implementation for `wchar_t'.  The external encoding is
determined by the `LC_CTYPE' category of the current locale or by the
`ccs' part of the mode specification given to `fopen', `fopen64',
`freopen', or `freopen64'.  How and when the conversion happens is
unspecified and it happens invisible to the user.

   Since a stream is created in the unoriented state it has at that
point no conversion associated with it.  The conversion which will be
used is determined by the `LC_CTYPE' category selected at the time the
stream is oriented.  If the locales are changed at the runtime this
might produce surprising results unless one pays attention.  This is
just another good reason to orient the stream explicitly as soon as
possible, perhaps with a call to `fwide'.


File: libc.info,  Node: Simple Output,  Next: Character Input,  Prev: Streams and I18N,  Up: I/O on Streams

Simple Output by Characters or Lines
====================================

   This section describes functions for performing character- and
line-oriented output.

   These narrow streams functions are declared in the header file
`stdio.h' and the wide stream functions in `wchar.h'.

 - Function: int fputc (int C, FILE *STREAM)
     The `fputc' function converts the character C to type `unsigned
     char', and writes it to the stream STREAM.  `EOF' is returned if a
     write error occurs; otherwise the character C is returned.

 - Function: wint_t fputwc (wchar_t WC, FILE *STREAM)
     The `fputwc' function writes the wide character WC to the stream
     STREAM.  `WEOF' is returned if a write error occurs; otherwise the
     character WC is returned.

 - Function: int fputc_unlocked (int C, FILE *STREAM)
     The `fputc_unlocked' function is equivalent to the `fputc'
     function except that it does not implicitly lock the stream.

 - Function: wint_t fputwc_unlocked (wint_t WC, FILE *STREAM)
     The `fputwc_unlocked' function is equivalent to the `fputwc'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int putc (int C, FILE *STREAM)
     This is just like `fputc', except that most systems implement it as
     a macro, making it faster.  One consequence is that it may
     evaluate the STREAM argument more than once, which is an exception
     to the general rule for macros.  `putc' is usually the best
     function to use for writing a single character.

 - Function: wint_t putwc (wchar_t WC, FILE *STREAM)
     This is just like `fputwc', except that it can be implement as a
     macro, making it faster.  One consequence is that it may evaluate
     the STREAM argument more than once, which is an exception to the
     general rule for macros.  `putwc' is usually the best function to
     use for writing a single wide character.

 - Function: int putc_unlocked (int C, FILE *STREAM)
     The `putc_unlocked' function is equivalent to the `putc' function
     except that it does not implicitly lock the stream.

 - Function: wint_t putwc_unlocked (wchar_t WC, FILE *STREAM)
     The `putwc_unlocked' function is equivalent to the `putwc'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int putchar (int C)
     The `putchar' function is equivalent to `putc' with `stdout' as
     the value of the STREAM argument.

 - Function: wint_t putwchar (wchar_t WC)
     The `putwchar' function is equivalent to `putwc' with `stdout' as
     the value of the STREAM argument.

 - Function: int putchar_unlocked (int C)
     The `putchar_unlocked' function is equivalent to the `putchar'
     function except that it does not implicitly lock the stream.

 - Function: wint_t putwchar_unlocked (wchar_t WC)
     The `putwchar_unlocked' function is equivalent to the `putwchar'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int fputs (const char *S, FILE *STREAM)
     The function `fputs' writes the string S to the stream STREAM.
     The terminating null character is not written.  This function does
     _not_ add a newline character, either.  It outputs only the
     characters in the string.

     This function returns `EOF' if a write error occurs, and otherwise
     a non-negative value.

     For example:

          fputs ("Are ", stdout);
          fputs ("you ", stdout);
          fputs ("hungry?\n", stdout);

     outputs the text `Are you hungry?' followed by a newline.

 - Function: int fputws (const wchar_t *WS, FILE *STREAM)
     The function `fputws' writes the wide character string WS to the
     stream STREAM.  The terminating null character is not written.
     This function does _not_ add a newline character, either.  It
     outputs only the characters in the string.

     This function returns `WEOF' if a write error occurs, and otherwise
     a non-negative value.

 - Function: int fputs_unlocked (const char *S, FILE *STREAM)
     The `fputs_unlocked' function is equivalent to the `fputs'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int fputws_unlocked (const wchar_t *WS, FILE *STREAM)
     The `fputws_unlocked' function is equivalent to the `fputws'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int puts (const char *S)
     The `puts' function writes the string S to the stream `stdout'
     followed by a newline.  The terminating null character of the
     string is not written.  (Note that `fputs' does _not_ write a
     newline as this function does.)

     `puts' is the most convenient function for printing simple
     messages.  For example:

          puts ("This is a message.");

     outputs the text `This is a message.' followed by a newline.

 - Function: int putw (int W, FILE *STREAM)
     This function writes the word W (that is, an `int') to STREAM.  It
     is provided for compatibility with SVID, but we recommend you use
     `fwrite' instead (*note Block Input/Output::).


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

Character Input
===============

   This section describes functions for performing character-oriented
input.  These narrow streams functions are declared in the header file
`stdio.h' and the wide character functions are declared in `wchar.h'.

   These functions return an `int' or `wint_t' value (for narrow and
wide stream functions respectively) that is either a character of
input, or the special value `EOF'/`WEOF' (usually -1).  For the narrow
stream functions it is important to store the result of these functions
in a variable of type `int' instead of `char', even when you plan to
use it only as a character.  Storing `EOF' in a `char' variable
truncates its value to the size of a character, so that it is no longer
distinguishable from the valid character `(char) -1'.  So always use an
`int' for the result of `getc' and friends, and check for `EOF' after
the call; once you've verified that the result is not `EOF', you can be
sure that it will fit in a `char' variable without loss of information.

 - Function: int fgetc (FILE *STREAM)
     This function reads the next character as an `unsigned char' from
     the stream STREAM and returns its value, converted to an `int'.
     If an end-of-file condition or read error occurs, `EOF' is
     returned instead.

 - Function: wint_t fgetwc (FILE *STREAM)
     This function reads the next wide character from the stream STREAM
     and returns its value.  If an end-of-file condition or read error
     occurs, `WEOF' is returned instead.

 - Function: int fgetc_unlocked (FILE *STREAM)
     The `fgetc_unlocked' function is equivalent to the `fgetc'
     function except that it does not implicitly lock the stream.

 - Function: wint_t fgetwc_unlocked (FILE *STREAM)
     The `fgetwc_unlocked' function is equivalent to the `fgetwc'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int getc (FILE *STREAM)
     This is just like `fgetc', except that it is permissible (and
     typical) for it to be implemented as a macro that evaluates the
     STREAM argument more than once.  `getc' is often highly optimized,
     so it is usually the best function to use to read a single
     character.

 - Function: wint_t getwc (FILE *STREAM)
     This is just like `fgetwc', except that it is permissible for it to
     be implemented as a macro that evaluates the STREAM argument more
     than once.  `getwc' can be highly optimized, so it is usually the
     best function to use to read a single wide character.

 - Function: int getc_unlocked (FILE *STREAM)
     The `getc_unlocked' function is equivalent to the `getc' function
     except that it does not implicitly lock the stream.

 - Function: wint_t getwc_unlocked (FILE *STREAM)
     The `getwc_unlocked' function is equivalent to the `getwc'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: int getchar (void)
     The `getchar' function is equivalent to `getc' with `stdin' as the
     value of the STREAM argument.

 - Function: wint_t getwchar (void)
     The `getwchar' function is equivalent to `getwc' with `stdin' as
     the value of the STREAM argument.

 - Function: int getchar_unlocked (void)
     The `getchar_unlocked' function is equivalent to the `getchar'
     function except that it does not implicitly lock the stream.

 - Function: wint_t getwchar_unlocked (void)
     The `getwchar_unlocked' function is equivalent to the `getwchar'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

   Here is an example of a function that does input using `fgetc'.  It
would work just as well using `getc' instead, or using `getchar ()'
instead of `fgetc (stdin)'.  The code would also work the same for the
wide character stream functions.

     int
     y_or_n_p (const char *question)
     {
       fputs (question, stdout);
       while (1)
         {
           int c, answer;
           /* Write a space to separate answer from question. */
           fputc (' ', stdout);
           /* Read the first character of the line.
              This should be the answer character, but might not be. */
           c = tolower (fgetc (stdin));
           answer = c;
           /* Discard rest of input line. */
           while (c != '\n' && c != EOF)
             c = fgetc (stdin);
           /* Obey the answer if it was valid. */
           if (answer == 'y')
             return 1;
           if (answer == 'n')
             return 0;
           /* Answer was invalid: ask for valid answer. */
           fputs ("Please answer y or n:", stdout);
         }
     }

 - Function: int getw (FILE *STREAM)
     This function reads a word (that is, an `int') from STREAM.  It's
     provided for compatibility with SVID.  We recommend you use
     `fread' instead (*note Block Input/Output::).  Unlike `getc', any
     `int' value could be a valid result.  `getw' returns `EOF' when it
     encounters end-of-file or an error, but there is no way to
     distinguish this from an input word with value -1.


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 is
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 without any bytes
     read, `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'.

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

     If the system is already at end of file when you call `fgetws',
     then the contents of the array WS 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 WS.

     *Warning:* If the input data has a null wide character (which are
     null bytes in the input stream), you can't tell.  So don't use
     `fgetws' 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.

 - Function: char * fgets_unlocked (char *S, int COUNT, FILE *STREAM)
     The `fgets_unlocked' function is equivalent to the `fgets'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

 - Function: wchar_t * fgetws_unlocked (wchar_t *WS, int COUNT, FILE
          *STREAM)
     The `fgetws_unlocked' function is equivalent to the `fgetws'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

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

 - Function: wint_t ungetwc (wint_t WC, FILE *STREAM)
     The `ungetwc' function behaves just like `ungetc' just that it
     pushes back a wide character.

   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 fread_unlocked (void *DATA, size_t SIZE, size_t
          COUNT, FILE *STREAM)
     The `fread_unlocked' function is equivalent to the `fread'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.

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

 - Function: size_t fwrite_unlocked (const void *DATA, size_t SIZE,
          size_t COUNT, FILE *STREAM)
     The `fwrite_unlocked' function is equivalent to the `fwrite'
     function except that it does not implicitly lock the stream.

     This function is a GNU extension.


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

