   This file documents the GNU C library.

   This is Edition 0.03, last updated 19 May 1993, of
`The GNU C Library Reference Manual', for Version 1.06 Beta.

   Copyright (C) 1993 Free Software Foundation, Inc.

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

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

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

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

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

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

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

     {
       char *variable, *value;

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

       ...
     }

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

   This section describes the miscellaneous input conversions.

   The `%p' conversion is used to read a pointer value.  It recognizes
the same syntax as is used by the `%p' output conversion for `printf'.
The corresponding argument should be of type `void **'; that is, the
address of a place to store a pointer.

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

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

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

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

Formatted Input Functions
-------------------------

   Here are the descriptions of the functions for performing formatted
input. Prototypes for these functions are in the header file `stdio.h'.

 -- Function: int scanf (const char *TEMPLATE, ...)
     The `scanf' function reads formatted input from the stream `stdin'
     under the control of the template string TEMPLATE. The optional
     arguments are pointers to the places which receive the resulting
     values.

     The return value is normally the number of successful assignments.
      If an end-of-file condition is detected before any matches are
     performed (including matches against whitespace and literal
     characters in the template), then `EOF' is returned.

 -- Function: int fscanf (FILE *STREAM, const char *TEMPLATE, ...)
     This function is just like `scanf', except that the input is read
     from the stream STREAM instead of `stdin'.

 -- Function: int sscanf (const char *S, const char *TEMPLATE, ...)
     This is like `scanf', except that the characters are taken from the
     null-terminated string S instead of from a stream.  Reaching the
     end of the string is treated as an end-of-file condition.

     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 receive a string read under control of the `%s'
     conversion.

Variable Arguments Input Functions
----------------------------------

   The functions `vscanf' and friends are provided so that you can
define your own variadic `scanf'-like functions that make use of the
same internals as the built-in formatted output functions. These
functions are analogous to the `vprintf' series of output functions.
See Variable Arguments Output, for important information on how to
use them.

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

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

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

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

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.

End-Of-File and Errors
======================

   Many of the functions described in this chapter return the value of
the macro `EOF' to indicate unsuccessful completion of the operation.
Since `EOF' is used to report both end of file and random errors, it's
often better to use the `feof' function to check explicitly for end of
file and `ferror' to check for errors.  These functions check
indicators that are part of the internal state of the stream object,
indicators set if the appropriate condition was detected by a previous
I/O operation on that stream.

   These symbols are declared in the header file `stdio.h'.

 -- Macro: int EOF
     This macro is an integer value that is returned by a number of
     functions to indicate an end-of-file condition, or some other
     error situation.  With the GNU library, `EOF' is `-1'. In other
     libraries, its value may be some other negative number.

 -- Function: void clearerr (FILE *STREAM)
     This function clears the end-of-file and error indicators for the
     stream STREAM.

     The file positioning functions (see File Positioning.) also
     clear the end-of-file indicator for the stream.

 -- Function: int feof (FILE *STREAM)
     The `feof' function returns nonzero if and only if the end-of-file
     indicator for the stream STREAM is set.

 -- Function: int ferror (FILE *STREAM)
     The `ferror' function returns nonzero if and only if the error
     indicator for the stream STREAM is set, indicating that an error
     has occurred on a previous operation on the stream.

   In addition to setting the error indicator associated with the
stream, the functions that operate on streams also set `errno' in the
same way as the corresponding low-level functions that operate on file
descriptors.  For example, all of the functions that perform output to a
stream--such as `fputc', `printf', and `fflush'--are implemented in
terms of `write', and all of the `errno' error conditions defined for
`write' are meaningful for these functions. For more information about
the descriptor-level I/O functions, see Low-Level I/O.

Text and Binary Streams
=======================

   The GNU system and other POSIX-compatible operating systems organize
all files as uniform sequences of characters.  However, some other
systems make a distinction between files containing text and files
containing binary data, and the input and output facilities of ANSI C
provide for this distinction.  This section tells you how to write
programs portable to such systems.

   When you open a stream, you can specify either a "text stream" or a
"binary stream".  You indicate that you want a binary stream by
specifying the `b' modifier in the OPENTYPE argument to `fopen'; see
Opening Streams.  Without this option, `fopen' opens the file
as a text stream.

   Text and binary streams differ in several ways:

   * The data read from a text stream is divided into "lines" which are
     terminated by newline (`'\n'') characters, while a binary stream is
     simply a long series of characters.  A text stream might on some
     systems fail to handle lines more than 254 characters long
     (including the terminating newline character).

   * On some systems, text files can contain only printing characters,
     horizontal tab characters, and newlines, and so text streams may
     not support other characters.  However, binary streams can handle
     any character value.

   * Space characters that are written immediately preceeding a newline
     character in a text stream may disappear when the file is read in
     again.

   * More generally, there need not be a one-to-one mapping between
     characters that are read from or written to a text stream, and the
     characters in the actual file.

   Since a binary stream is always more capable and more predictable
than a text stream, you might wonder what purpose text streams serve.
Why not simply always use binary streams?  The answer is that on these
operating systems, text and binary streams use different file formats,
and the only way to read or write "an ordinary file of text" that can
work with other text-oriented programs is through a text stream.

   In the GNU library, and on all POSIX systems, there is no difference
between text streams and binary streams.  When you open a stream, you
get the same kind of stream regardless of whether you ask for binary.
This stream can handle any file content, and has none of the
restrictions that text streams sometimes have.

File Positioning
================

   The "file position" of a stream describes where in the file the
stream is currently reading or writing.  I/O on the stream advances the
file position through the file.  In the GNU system, the file position is
represented as an integer, which counts the number of bytes from the
beginning of the file.  See File Position.

   During I/O to an ordinary disk file, you can change the file position
whenever you wish, so as to read or write any portion of the file.  Some
other kinds of files may also permit this.  Files which support changing
the file position are sometimes referred to as "random-access" files.

   You can use the functions in this section to examine or modify the
file position indicator associated with a stream.  The symbols listed
below are declared in the header file `stdio.h'.

 -- Function: long int ftell (FILE *STREAM)
     This function returns the current file position of the stream
     STREAM.

     This function can fail if the stream doesn't support file
     positioning, or if the file position can't be represented in a
     `long int', and possibly for other reasons as well.  If a failure
     occurs, a value of `-1' is returned.

 -- Function: int fseek (FILE *STREAM, long int OFFSET, int WHENCE)
     The `fseek' function is used to change the file position of the
     stream STREAM.  The value of WHENCE must be one of the constants
     `SEEK_SET', `SEEK_CUR', or `SEEK_END', to indicate whether the
     OFFSET is relative to the beginning of the file, the current file
     position, or the end of the file, respectively.

     This function returns a value of zero if the operation was
     successful, and a nonzero value to indicate failure.  A successful
     call also clears the end-of-file indicator of STREAM and discards
     any characters that were "pushed back" by the use of `ungetc'.

     `fseek' either flushes any buffered output before setting the file
     position or else remembers it so it will be written later in its
     proper place in the file.

   *Portability Note:* In non-POSIX systems, `ftell' and `fseek' might
work reliably only on binary streams.  See Binary Streams.

   The following symbolic constants are defined for use as the WHENCE
argument to `fseek'.  They are also used with the `lseek' function
(see I/O Primitives.) and to specify offsets for file locks (see
Control Operations.).

 -- Macro: int SEEK_SET
     This is an integer constant which, when used as the WHENCE
     argument to the `fseek' function, specifies that the offset
     provided is relative to the beginning of the file.

 -- Macro: int SEEK_CUR
     This is an integer constant which, when used as the WHENCE
     argument to the `fseek' function, specifies that the offset
     provided is relative to the current file position.

 -- Macro: int SEEK_END
     This is an integer constant which, when used as the WHENCE
     argument to the `fseek' function, specifies that the offset
     provided is relative to the end of the file.

 -- Function: void rewind (FILE *STREAM)
     The `rewind' function positions the stream STREAM at the begining
     of the file.  It is equivalent to calling `fseek' on the STREAM
     with an OFFSET argument of `0L' and a WHENCE argument of
     `SEEK_SET', except that the return value is discarded and the
     error indicator for the stream is reset.

   These three aliases for the `SEEK_...' constants exist for the sake
of compatibility with older BSD systems.  They are defined in two
different header files: `fcntl.h' and `sys/file.h'.

`L_SET'
     An alias for `SEEK_SET'.

`L_INCR'
     An alias for `SEEK_CUR'.

`L_XTND'
     An alias for `SEEK_END'.

Portable File-Position Functions
================================

   On the GNU system, the file position is truly a character count.  You
can specify any character count value as an argument to `fseek' and get
reliable results for any random access file.  However, some ANSI C
systems do not represent file positions in this way.

   On some systems where text streams truly differ from binary streams,
it is impossible to represent the file position of a text stream as a
count of characters from the beginning of the file.  For example, the
file position on some systems must encode both a record offset within
the file, and a character offset within the record.

   As a consequence, if you want your programs to be portable to these
systems, you must observe certain rules:

   * The value returned from `ftell' on a text stream has no predictable
     relationship to the number of characters you have read so far.
     The only thing you can rely on is that you can use it subsequently
     as the OFFSET argument to `fseek' to move back to the same file
     position.

   * In a call to `fseek' on a text stream, either the OFFSET must
     either be zero; or WHENCE must be `SEEK_SET' and the OFFSET must
     be the result of an earlier call to `ftell' on the same stream.

   * The value of the file position indicator of a text stream is
     undefined while there are characters that have been pushed back
     with `ungetc' that haven't been read or discarded.  See
     Unreading.

   But even if you observe these rules, you may still have trouble for
long files, because `ftell' and `fseek' use a `long int' value to
represent the file position.  This type may not have room to encode all
the file positions in a large file.

   So if you do want to support systems with peculiar encodings for the
file positions, it is better to use the functions `fgetpos' and
`fsetpos' instead.  These functions represent the file position using
the data type `fpos_t', whose internal representation varies from
system to system.

   These symbols are declared in the header file `stdio.h'.

 -- Data Type: fpos_t
     This is the type of an object that can encode information about the
     file position of a stream, for use by the functions `fgetpos' and
     `fsetpos'.

     In the GNU system, `fpos_t' is equivalent to `off_t' or `long
     int'.  In other systems, it might have a different internal
     representation.

 -- Function: int fgetpos (FILE *STREAM, fpos_t *POSITION)
     This function stores the value of the file position indicator for
     the stream STREAM in the `fpos_t' object pointed to by POSITION.
     If successful, `fgetpos' returns zero; otherwise it returns a
     nonzero value and stores an implementation-defined positive value
     in `errno'.

 -- Function: int fsetpos (FILE *STREAM, const fpos_t POSITION)
     This function sets the file position indicator for the stream
     STREAM to the position POSITION, which must have been set by a
     previous call to `fgetpos' on the same stream.  If successful,
     `fsetpos' clears the end-of-file indicator on the stream, discards
     any characters that were "pushed back" by the use of `ungetc', and
     returns a value of zero.  Otherwise, `fsetpos' returns a nonzero
     value and stores an implementation-defined positive value in
     `errno'.

Stream Buffering
================

   Characters that are written to a stream are normally accumulated and
transmitted asynchronously to the file in a block, instead of appearing
as soon as they are output by the application program.  Similarly,
streams often retrieve input from the host environment in blocks rather
than on a character-by-character basis.  This is called "buffering".

   If you are writing programs that do interactive input and output
using streams, you need to understand how buffering works when you
design the user interface to your program.  Otherwise, you might find
that output (such as progress or prompt messages) doesn't appear when
you intended it to, or that input typed by the user is made available
by lines instead of by single characters, or other unexpected behavior.

   This section deals only with controlling when characters are
transmitted between the stream and the file or device, and *not* with
how things like echoing, flow control, and the like are handled on
specific classes of devices.  For information on common control
operations on terminal devices, see Low-Level Terminal Interface.

   You can bypass the stream buffering facilities altogether by using
the low-level input and output functions that operate on file
descriptors instead.  See Low-Level I/O.

Buffering Concepts
------------------

   There are three different kinds of buffering strategies:

   * Characters written to or read from an "unbuffered" stream are
     transmitted individually to or from the file as soon as possible.

   * Characters written to or read from a "line buffered" stream are
     transmitted to or from the file in blocks when a newline character
     is encountered.

   * Characters written to or read from a "fully buffered" stream are
     transmitted to or from the file in blocks of arbitrary size.

   Newly opened streams are normally fully buffered, with one
exception: a stream connected to an interactive device such as a
terminal is initially line buffered.  See Controlling Buffering,
for information on how to select a different kind of buffering.

   The use of line buffering for interactive devices implies that output
messages ending in a newline will appear immediately--which is usually
what you want.  Output that doesn't end in a newline might or might not
show up immediately, so if you want them to appear immediately, you
should flush buffered output explicitly with `fflush', as described in
Flushing Buffers.

   Line buffering is a good default for terminal input as well, because
most interactive programs read commands that are normally single lines.
The program should be able to execute each line right away.  A line
buffered stream permits this, whereas a fully buffered stream would
always read enough text to fill the buffer before allowing the program
to read any of it.  Line buffering also fits in with the usual
input-editing facilities of most operating systems, which work within a
line of input.

   Some programs need an unbuffered terminal input stream.  These
include programs that read single-character commands (like Emacs) and
programs that do their own input editing (such as those that use
readline).  In order to read a character at a time, it is not enough to
turn off buffering in the input stream; you must also turn off input
editing in the operating system.  This requires changing the terminal
mode (see Terminal Modes.).  If you want to change the terminal
modes, you have to do this separately--merely using an unbuffered
stream does not change the modes.

Flushing Buffers
----------------

   "Flushing" output on a buffered stream means transmitting all
accumulated characters to the file.  There are many circumstances when
buffered output on a stream is flushed automatically:

   * When you try to do output and the output buffer is full.

   * When the stream is closed.  See Closing Streams.

   * When the program terminates by calling `exit'. See Normal Termination.

   * When a newline is written, if the stream is line buffered.

   * Whenever an input operation on *any* stream actually reads data
     from its file.

   If you want to flush the buffered output at another time, call
`fflush', which is declared in the header file `stdio.h'.

 -- Function: int fflush (FILE *STREAM)
     This function causes any buffered output on STREAM to be delivered
     to the file.  If STREAM is a null pointer, then `fflush' causes
     buffered output on *all* open output streams to be flushed.

     This function returns `EOF' if a write error occurs, or zero
     otherwise.

   *Compatibility Note:* Some brain-damaged operating systems have been
known to be so thoroughly fixated on line-oriented input and output
that flushing a line buffered stream causes a newline to be written!
Fortunately, this "feature" seems to be becoming less common.  You do
not need to worry about this in the GNU system.

Controlling Which Kind of Buffering
-----------------------------------

   After opening a stream (but before any other operations have been
performed on it), you can explicitly specify what kind of buffering you
want it to have using the `setvbuf' function.

   The facilities listed in this section are declared in the header
file `stdio.h'.

 -- Function: int setvbuf (FILE *STREAM, char *BUF, int MODE, size_t
          SIZE)
     This function is used to specify that the stream STREAM should
     have the buffering mode MODE, which can be either `_IOFBF' (for
     full buffering), `_IOLBF' (for line buffering), or `_IONBF' (for
     unbuffered input/output).

     If you specify a null pointer as the BUF argument, then `setvbuf'
     allocates a buffer itself using `malloc'.  This buffer will be
     freed when you close the stream.

     Otherwise, BUF should be a character array that can hold at least
     SIZE characters.  You should not free the space for this array as
     long as the stream remains open and this array remains its buffer.
      You should usually either allocate it statically, or `malloc'
     (see Unconstrained Allocation.) the buffer.  Using an
     automatic array is not a good idea unless you close the file
     before exiting the block that declares the array.

     While the array remains a stream buffer, the stream I/O functions
     will use the buffer for their internal purposes.  You shouldn't
     try to access the values in the array directly while the stream is
     using it for buffering.

     The `setvbuf' function returns zero on success, or a nonzero value
     if the value of MODE is not valid or if the request could not be
     honored.

 -- Macro: int _IOFBF
     The value of this macro is an integer constant expression that can
     be used as the MODE argument to the `setvbuf' function to specify
     that the stream should be fully buffered.

 -- Macro: int _IOLBF
     The value of this macro is an integer constant expression that can
     be used as the MODE argument to the `setvbuf' function to specify
     that the stream should be line buffered.

 -- Macro: int _IONBF
     The value of this macro is an integer constant expression that can
     be used as the MODE argument to the `setvbuf' function to specify
     that the stream should be unbuffered.

 -- Macro: int BUFSIZ
     The value of this macro is an integer constant expression that is
     good to use for the SIZE argument to `setvbuf'.  This value is
     guaranteed to be at least `256'.

     The value of `BUFSIZ' is chosen on each system so as to make stream
     I/O efficient.  So it is a good idea to use `BUFSIZ' as the size
     for the buffer when you call `setvbuf'.

     Actually, you can get an even better value to use for the buffer
     size by means of the `fstat' system call: it is found in the
     `st_blksize' field of the file attributes.  See Attribute Meanings.

     Sometimes people also use `BUFSIZ' as the allocation size of
     buffers used for related purposes, such as strings used to receive
     a line of input with `fgets' (see Character Input.).  There is
     no particular reason to use `BUFSIZ' for this instead of any other
     integer, except that it might lead to doing I/O in chunks of an
     efficient size.

 -- Function: void setbuf (FILE *STREAM, char *BUF)
     If BUF is a null pointer, the effect of this function is
     equivalent to calling `setvbuf' with a MODE argument of `_IONBF'.
     Otherwise, it is equivalent to calling `setvbuf' with BUF, and a
     MODE of `_IOFBF' and a SIZE argument of `BUFSIZ'.

     The `setbuf' function is provided for compatibility with old code;
     use `setvbuf' in all new programs.

 -- Function: void setbuffer (FILE *STREAM, char *BUF, size_t SIZE)
     If BUF is a null pointer, this function makes STREAM unbuffered.
     Otherwise, it makes STREAM fully buffered using BUF as the buffer.
      The SIZE argument specifies the length of BUF.

     This function is provided for compatibility with old BSD code.  Use
     `setvbuf' instead.

 -- Function: void setlinebuf (FILE *STREAM)
     This function makes STREAM be line buffered, and allocates the
     buffer for you.

     This function is provided for compatibility with old BSD code.  Use
     `setvbuf' instead.

Temporary Files
===============

   If you need to use a temporary file in your program, you can use the
`tmpfile' function to open it.  Or you can use the `tmpnam' function
make a name for a temporary file and then open it in the usual way with
`fopen'.

   These facilities are declared in the header file `stdio.h'.

 -- Function: FILE * tmpfile (void)
     This function creates a temporary binary file for update mode, as
     if by calling `fopen' with mode `"wb+"'.  The file is deleted
     automatically when it is closed or when the program terminates.
     (On some other ANSI C systems the file may fail to be deleted if
     the program terminates abnormally).

 -- Function: char * tmpnam (char *RESULT)
     This function constructs and returns a file name that is a valid
     file name and that does not name any existing file.  If the RESULT
     argument is a null pointer, the return value is a pointer to an
     internal static string, which might be modified by subsequent
     calls.  Otherwise, the RESULT argument should be a pointer to an
     array of at least `L_tmpnam' characters, and the result is written
     into that array.

     It is possible for `tmpnam' to fail if you call it too many times.
     This is because the fixed length of a temporary file name gives
     room for only a finite number of different names.  If `tmpnam'
     fails, it returns a null pointer.

 -- Macro: int L_tmpnam
     The value of this macro is an integer constant expression that
     represents the minimum allocation size of a string large enough to
     hold the file name generated by the `tmpnam' function.

 -- Macro: int TMP_MAX
     The macro `TMP_MAX' is a lower bound for how many temporary names
     you can create with `tmpnam'.  You can rely on being able to call
     `tmpnam' at least this many times before it might fail saying you
     have made too many temporary file names.

     With the GNU library, you can create a very large number of
     temporary file names--if you actually create the files, you will
     probably run out of disk space before you run out of names.  Some
     other systems have a fixed, small limit on the number of temporary
     files.  The limit is never less than `25'.

 -- Function: char * tempnam (const char *DIR, const char *PREFIX)
     This function generates a unique temporary filename.  If PREFIX is
     not a null pointer, up to five characters of this string are used
     as a prefix for the file name.

     The directory prefix for the temporary file name is determined by
     testing each of the following, in sequence.  The directory must
     exist and be writable.

        * The environment variable `TMPDIR', if it is defined.

        * The DIR argument, if it is not a null pointer.

        * The value of the `P_tmpdir' macro.

        * The directory `/tmp'.

     This function is defined for SVID compatibility.

 -- SVID Macro: char * P_tmpdir
     This macro is the name of the default directory for temporary
     files.

Other Kinds of Streams
======================

   The GNU library provides ways for you to define additional kinds of
streams that do not necessarily correspond to an open file.

   One such type of stream takes input from or writes output to a
string. These kinds of streams are used internally to implement the
`sprintf' and `sscanf' functions.  You can also create such a stream
explicitly, using the functions described in String Streams.

   More generally, you can define streams that do input/output to
arbitrary objects using functions supplied by your program.  This
protocol is discussed in Custom Streams.

   *Portability Note:* The facilities described in this section are
specific to GNU.  Other systems or C implementations might or might not
provide equivalent functionality.

String Streams
--------------

   The `fmemopen' and `open_memstream' functions allow you to do I/O to
a string or memory buffer.  These facilities are declared in `stdio.h'.

 -- Function: FILE * fmemopen (void *BUF, size_t SIZE, const char
          *OPENTYPE)
     This function opens a stream that allows the access specified by
     the OPENTYPE argument, that reads from or writes to the buffer
     specified by the argument BUF.  This array must be at least SIZE
     bytes long.

     If you specify a null pointer as the BUF argument, `fmemopen'
     dynamically allocates (as with `malloc'; see Unconstrained Allocation.)
     an array SIZE bytes long.  This is really only
     useful if you are going to write things to the buffer and then
     read them back in again, because you have no way of actually
     getting a pointer to the buffer (for this, try `open_memstream',
     below).  The buffer is freed when the stream is open.

     The argument OPENTYPE is the same as in `fopen' (see Opening Streams).
     If the OPENTYPE specifies append mode, then the
     initial file position is set to the first null character in the
     buffer.  Otherwise the initial file position is at the beginning
     of the buffer.

     When a stream open for writing is flushed or closed, a null
     character (zero byte) is written at the end of the buffer if it
     fits.  You should add an extra byte to the SIZE argument to
     account for this. Attempts to write more than SIZE bytes to the
     buffer result in an error.

     For a stream open for reading, null characters (zero bytes) in the
     buffer do not count as "end of file".  Read operations indicate
     end of file only when the file position advances past SIZE bytes.
     So, if you want to read characters from a null-terminated string,
     you should supply the length of the string as the SIZE argument.

   Here is an example of using `fmemopen' to create a stream for
reading from a string:

     #include <stdio.h>

     static char buffer[] = "foobar";

     int
     main (void)
     {
       int ch;
       FILE *stream;

       stream = fmemopen (buffer, strlen (buffer), "r");
       while ((ch = fgetc (stream)) != EOF)
         printf ("Got %c\n", ch);
       fclose (stream);

       return 0;
     }

   This program produces the following output:

     Got f
     Got o
     Got o
     Got b
     Got a
     Got r

 -- Function: FILE * open_memstream (char **PTR, size_t *SIZELOC)
     This function opens a stream for writing to a buffer.  The buffer
     is allocated dynamically (as with `malloc'; see Unconstrained Allocation.)
     and grown as necessary.

     When the stream is closed with `fclose' or flushed with `fflush',
     the locations PTR and SIZELOC are updated to contain the pointer
     to the buffer and its size.  The values thus stored remain valid
     only as long as no further output on the stream takes place.  If
     you do more output, you must flush the stream again to store new
     values before you use them again.

     A null character is written at the end of the buffer.  This null
     character is *not* included in the size value stored at SIZELOC.

     You can move the stream's file position with `fseek' (see File Positioning.).
     Moving the file position past the end of the data
     already written fills the intervening space with zeroes.

   Here is an example of using `open_memstream':

     #include <stdio.h>

     int
     main (void)
     {
       char *bp;
       size_t size;
       FILE *stream;

       stream = open_memstream (&bp, &size);
       fprintf (stream, "hello");
       fflush (stream);
       printf ("buf = %s, size = %d\n", bp, size);
       fprintf (stream, ", world");
       fclose (stream);
       printf ("buf = %s, size = %d\n", bp, size);

       return 0;
     }

   This program produces the following output:

     buf = `hello', size = 5
     buf = `hello, world', size = 12

Obstack Streams
---------------

   You can open an output stream that puts it data in an obstack. See
Obstacks.

 -- Function: FILE * open_obstack_stream (struct obstack *OBSTACK)
     This function opens a stream for writing data into the obstack
     OBSTACK. This starts an object in the obstack and makes it grow as
     data is written (see Growing Objects.).

     Calling `fflush' on this stream updates the current size of the
     object to match the amount of data that has been written.  After a
     call to `fflush', you can examine the object temporarily.

     You can move the file position of an obstack stream with `fseek'
     (see File Positioning.).  Moving the file position past the
     end of the data written fills the intervening space with zeros.

     To make the object permanent, update the obstack with `fflush', and
     then use `obstack_finish' to finalize the object and get its
     address. The following write to the stream starts a new object in
     the obstack, and later writes add to that object until you do
     another `fflush' and `obstack_finish'.

     But how do you find out how long the object is?  You can get the
     length in bytes by calling `obstack_object_size' (see Status of an Obstack.),
     or you can null-terminate the object like this:

          obstack_1grow (OBSTACK, 0);

     Whichever one you do, you must do it *before* calling
     `obstack_finish'.  (You can do both if you wish.)

   Here is a sample function that uses `open_obstack_stream':

     char *
     make_message_string (const char *a, int b)
     {
       FILE *stream = open_obstack_stream (&message_obstack);
       output_task (stream);
       fprintf (stream, ": ");
       fprintf (stream, a, b);
       fprintf (stream, "\n");
       fclose (stream);
       obstack_1grow (&message_obstack, 0);
       return obstack_finish (&message_obstack);
     }

Programming Your Own Custom Streams
-----------------------------------

   This section describes how you can make a stream that gets input
from an arbitrary data source or writes output to an arbitrary data sink
programmed by you.  We call these "custom streams".

Custom Streams and Cookies
..........................

   Inside every custom stream is a special object called the "cookie".
This is an object supplied by you which records where to fetch or store
the data read or written.  It is up to you to define a data type to use
for the cookie.  The stream functions in the library never refer
directly to its contents, and they don't even know what the type is;
they record its address with type `void *'.

   To implement a custom stream, you must specify *how* to fetch or
store the data in the specified place.  You do this by defining "hook
functions" to read, write, change "file position", and close the
stream.  All four of these functions will be passed the stream's cookie
so they can tell where to fetch or store the data.  The library
functions don't know what's inside the cookie, but your functions will
know.

   When you create a custom stream, you must specify the cookie pointer,
and also the four hook functions stored in a structure of type `struct
cookie_io_functions'.

   These facilities are declared in `stdio.h'.

 -- Data Type: struct cookie_io_functions
     This is a structure type that holds the functions that define the
     communications protocol between the stream and its cookie.  It has
     the following members:

    `cookie_read_function *read'
          This is the function that reads data from the cookie.  If the
          value is a null pointer instead of a function, then read
          operations on ths stream always return `EOF'.

    `cookie_write_function *write'
          This is the function that writes data to the cookie.  If the
          value is a null pointer instead of a function, then data
          written to the stream is discarded.

    `cookie_seek_function *seek'
          This is the function that performs the equivalent of file
          positioning on the cookie.  If the value is a null pointer
          instead of a function, calls to `fseek' on this stream return
          an `ESPIPE' error.

    `cookie_close_function *close'
          This function performs any appropriate cleanup on the cookie
          when closing the stream.  If the value is a null pointer
          instead of a function, nothing special is done to close the
          cookie when the stream is closed.

 -- Function: FILE * fopencookie (void *COOKIE, const char *OPENTYPE,
          struct cookie_functions IO_FUNCTIONS)
     This function actually creates the stream for communicating with
     the COOKIE using the functions in the IO_FUNCTIONS argument. The
     OPENTYPE argument is interpreted as for `fopen'; see Opening Streams.
     (But note that the "truncate on open" option is
     ignored.)  The new stream is fully buffered.

     The `fopencookie' function returns the newly created stream, or a
     null pointer in case of an error.

Custom Stream Hook Functions
............................

   Here are more details on how you should define the four hook
functions that a custom stream needs.

   You should define the function to read data from the cookie as:

     ssize_t READER (void *COOKIE, void *BUFFER, size_t SIZE)

   This is very similar to the `read' function; see I/O Primitives.
Your function should transfer up to SIZE bytes into the
BUFFER, and return the number of bytes read, or zero to indicate
end-of-file.  You can return a value of `-1' to indicate an error.

   You should define the function to write data to the cookie as:

     ssize_t WRITER (void *COOKIE, const void *BUFFER, size_t SIZE)

   This is very similar to the `write' function; see I/O Primitives.
Your function should transfer up to SIZE bytes from the
buffer, and return the number of bytes written.  You can return a value
of `-1' to indicate an error.

   You should define the function to perform seek operations on the
cookie as:

     int SEEKER (void *COOKIE, fpos_t *POSITION, int WHENCE)

   For this function, the POSITION and WHENCE arguments are interpreted
as for `fgetpos'; see Portable Positioning.  In the GNU
library, `fpos_t' is equivalent to `off_t' or `long int', and simply
represents the number of bytes from the beginning of the file.

   After doing the seek operation, your function should store the
resulting file position relative to the beginning of the file in
POSITION. Your function should return a value of `0' on success and `-1'
to indicate an error.

   You should define the function to do cleanup operations on the cookie
appropriate for closing the stream as:

     int CLEANER (void *COOKIE)

   Your function should return `-1' to indicate an error, and `0'
otherwise.

 -- Data Type: cookie_read_function
     This is the data type that the read function for a custom stream
     should have. If you declare the function as shown above, this is
     the type it will have.

 -- Data Type: cookie_write_function
     The data type of the write function for a custom stream.

 -- Data Type: cookie_seek_function
     The data type of the seek function for a custom stream.

 -- Data Type: cookie_close_function
     The data type of the close function for a custom stream.

Low-Level Input/Output
**********************

   This chapter describes functions for performing low-level
input/output operations on file descriptors.  These functions include
the primitives for the higher-level I/O functions described in
I/O on Streams, as well as functions for performing low-level control
operations for which there are no equivalents on streams.

   Stream-level I/O is more flexible and usually more convenient;
therefore, programmers generally use the descriptor-level functions only
when necessary.  These are some of the usual reasons:

   * For reading binary files in large chunks.

   * For reading an entire file into core before parsing it.

   * To perform operations other than data transfer, which can only be
     done with a descriptor.  (You can use `fileno' to get the
     descriptor corresponding to a stream.)

   * To pass descriptors to a child process.  (The child can create its
     own stream to use a descriptor that it inherits, but cannot
     inherit a stream directly.)