   This file documents the GNU C library.

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

   Copyright (C) 1993, 1994 Free Software Foundation, Inc.

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

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

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

Search Functions
================

   This section describes library functions which perform various kinds
of searching operations on strings and arrays.  These functions are
declared in the header file `string.h'.

 - Function: void * memchr (const void *BLOCK, int C, size_t SIZE)
     This function finds the first occurrence of the byte C (converted
     to an `unsigned char') in the initial SIZE bytes of the object
     beginning at BLOCK.  The return value is a pointer to the located
     byte, or a null pointer if no match was found.

 - Function: char * strchr (const char *STRING, int C)
     The `strchr' function finds the first occurrence of the character
     C (converted to a `char') in the null-terminated string beginning
     at STRING.  The return value is a pointer to the located
     character, or a null pointer if no match was found.

     For example,
          strchr ("hello, world", 'l')
              => "llo, world"
          strchr ("hello, world", '?')
              => NULL

     The terminating null character is considered to be part of the
     string, so you can use this function get a pointer to the end of a
     string by specifying a null character as the value of the C
     argument.

 - Function: char * index (const char *STRING, int C)
     `index' is another name for `strchr'; they are exactly the same.

 - Function: char * strrchr (const char *STRING, int C)
     The function `strrchr' is like `strchr', except that it searches
     backwards from the end of the string STRING (instead of forwards
     from the front).

     For example,
          strrchr ("hello, world", 'l')
              => "ld"

 - Function: char * rindex (const char *STRING, int C)
     `rindex' is another name for `strrchr'; they are exactly the same.

 - Function: char * strstr (const char *HAYSTACK, const char *NEEDLE)
     This is like `strchr', except that it searches HAYSTACK for a
     substring NEEDLE rather than just a single character.  It returns
     a pointer into the string HAYSTACK that is the first character of
     the substring, or a null pointer if no match was found.  If NEEDLE
     is an empty string, the function returns HAYSTACK.

     For example,
          strstr ("hello, world", "l")
              => "llo, world"
          strstr ("hello, world", "wo")
              => "world"

 - Function: void * memmem (const void *NEEDLE, size_t NEEDLE-LEN,
          const void *HAYSTACK, size_t HAYSTACK-LEN)
     This is like `strstr', but NEEDLE and HAYSTACK are byte arrays
     rather than null-terminated strings.  NEEDLE-LEN is the length of
     NEEDLE and HAYSTACK-LEN is the length of HAYSTACK.

     This function is a GNU extension.

 - Function: size_t strspn (const char *STRING, const char *SKIPSET)
     The `strspn' ("string span") function returns the length of the
     initial substring of STRING that consists entirely of characters
     that are members of the set specified by the string SKIPSET.  The
     order of the characters in SKIPSET is not important.

     For example,
          strspn ("hello, world", "abcdefghijklmnopqrstuvwxyz")
              => 5

 - Function: size_t strcspn (const char *STRING, const char *STOPSET)
     The `strcspn' ("string complement span") function returns the
     length of the initial substring of STRING that consists entirely
     of characters that are *not* members of the set specified by the
     string STOPSET.  (In other words, it returns the offset of the
     first character in STRING that is a member of the set STOPSET.)

     For example,
          strcspn ("hello, world", " \t\n,.;!?")
              => 5

 - Function: char * strpbrk (const char *STRING, const char *STOPSET)
     The `strpbrk' ("string pointer break") function is related to
     `strcspn', except that it returns a pointer to the first character
     in STRING that is a member of the set STOPSET instead of the
     length of the initial substring.  It returns a null pointer if no
     such character from STOPSET is found.

     For example,

          strpbrk ("hello, world", " \t\n,.;!?")
              => ", world"

Finding Tokens in a String
==========================

   It's fairly common for programs to have a need to do some simple
kinds of lexical analysis and parsing, such as splitting a command
string up into tokens.  You can do this with the `strtok' function,
declared in the header file `string.h'.

 - Function: char * strtok (char *NEWSTRING, const char *DELIMITERS)
     A string can be split into tokens by making a series of calls to
     the function `strtok'.

     The string to be split up is passed as the NEWSTRING argument on
     the first call only.  The `strtok' function uses this to set up
     some internal state information.  Subsequent calls to get
     additional tokens from the same string are indicated by passing a
     null pointer as the NEWSTRING argument.  Calling `strtok' with
     another non-null NEWSTRING argument reinitializes the state
     information.  It is guaranteed that no other library function ever
     calls `strtok' behind your back (which would mess up this internal
     state information).

     The DELIMITERS argument is a string that specifies a set of
     delimiters that may surround the token being extracted.  All the
     initial characters that are members of this set are discarded.
     The first character that is *not* a member of this set of
     delimiters marks the beginning of the next token.  The end of the
     token is found by looking for the next character that is a member
     of the delimiter set.  This character in the original string
     NEWSTRING is overwritten by a null character, and the pointer to
     the beginning of the token in NEWSTRING is returned.

     On the next call to `strtok', the searching begins at the next
     character beyond the one that marked the end of the previous token.
     Note that the set of delimiters DELIMITERS do not have to be the
     same on every call in a series of calls to `strtok'.

     If the end of the string NEWSTRING is reached, or if the remainder
     of string consists only of delimiter characters, `strtok' returns
     a null pointer.

   *Warning:* Since `strtok' alters the string it is parsing, you
always copy the string to a temporary buffer before parsing it with
`strtok'.  If you allow `strtok' to modify a string that came from
another part of your program, you are asking for trouble; that string
may be part of a data structure that could be used for other purposes
during the parsing, when alteration by `strtok' makes the data
structure temporarily inaccurate.

   The string that you are operating on might even be a constant.  Then
when `strtok' tries to modify it, your program will get a fatal signal
for writing in read-only memory.  See Program Error Signals.

   This is a special case of a general principle: if a part of a program
does not have as its purpose the modification of a certain data
structure, then it is error-prone to modify the data structure
temporarily.

   The function `strtok' is not reentrant.  See Nonreentrancy, for
a discussion of where and why reentrancy is important.

   Here is a simple example showing the use of `strtok'.

     #include <string.h>
     #include <stddef.h>

     ...

     char string[] = "words separated by spaces -- and, punctuation!";
     const char delimiters[] = " .,;:!-";
     char *token;

     ...

     token = strtok (string, delimiters);  /* token => "words" */
     token = strtok (NULL, delimiters);    /* token => "separated" */
     token = strtok (NULL, delimiters);    /* token => "by" */
     token = strtok (NULL, delimiters);    /* token => "spaces" */
     token = strtok (NULL, delimiters);    /* token => "and" */
     token = strtok (NULL, delimiters);    /* token => "punctuation" */
     token = strtok (NULL, delimiters);    /* token => NULL */

Input/Output Overview
*********************

   Most programs need to do either input (reading data) or output
(writing data), or most frequently both, in order to do anything
useful.  The GNU C library provides such a large selection of input and
output functions that the hardest part is often deciding which function
is most appropriate!

   This chapter introduces concepts and terminology relating to input
and output.  Other chapters relating to the GNU I/O facilities are:

   * See I/O on Streams, which covers the high-level functions that
     operate on streams, including formatted input and output.

   * See Low-Level I/O, which covers the basic I/O and control
     functions on file descriptors.

   * See File System Interface, which covers functions for
     operating on directories and for manipulating file attributes such
     as access modes and ownership.

   * See Pipes and FIFOs, which includes information on the basic
     interprocess communication facilities.

   * See Sockets, which covers a more complicated interprocess
     communication facility with support for networking.

   * See Low-Level Terminal Interface, which covers functions for
     changing how input and output to terminal or other serial devices
     are processed.

Input/Output Concepts
=====================

   Before you can read or write the contents of a file, you must
establish a connection or communications channel to the file.  This
process is called "opening" the file.  You can open a file for reading,
writing, or both.

   The connection to an open file is represented either as a stream or
as a file descriptor.  You pass this as an argument to the functions
that do the actual read or write operations, to tell them which file to
operate on.  Certain functions expect streams, and others are designed
to operate on file descriptors.

   When you have finished reading to or writing from the file, you can
terminate the connection by "closing" the file.  Once you have closed a
stream or file descriptor, you cannot do any more input or output
operations on it.

Streams and File Descriptors
----------------------------

   When you want to do input or output to a file, you have a choice of
two basic mechanisms for representing the connection between your
program and the file: file descriptors and streams.  File descriptors
are represented as objects of type `int', while streams are represented
as `FILE *' objects.

   File descriptors provide a primitive, low-level interface to input
and output operations.  Both file descriptors and streams can represent
a connection to a device (such as a terminal), or a pipe or socket for
communicating with another process, as well as a normal file.  But, if
you want to do control operations that are specific to a particular kind
of device, you must use a file descriptor; there are no facilities to
use streams in this way.  You must also use file descriptors if your
program needs to do input or output in special modes, such as
nonblocking (or polled) input (see File Status Flags.).

   Streams provide a higher-level interface, layered on top of the
primitive file descriptor facilities.  The stream interface treats all
kinds of files pretty much alike--the sole exception being the three
styles of buffering that you can choose (see Stream Buffering.).

   The main advantage of using the stream interface is that the set of
functions for performing actual input and output operations (as opposed
to control operations) on streams is much richer and more powerful than
the corresponding facilities for file descriptors.  The file descriptor
interface provides only simple functions for transferring blocks of
characters, but the stream interface also provides powerful formatted
input and output functions (`printf' and `scanf') as well as functions
for character- and line-oriented input and output.

   Since streams are implemented in terms of file descriptors, you can
extract the file descriptor from a stream and perform low-level
operations directly on the file descriptor.  You can also initially open
a connection as a file descriptor and then make a stream associated with
that file descriptor.

   In general, you should stick with using streams rather than file
descriptors, unless there is some specific operation you want to do that
can only be done on a file descriptor.  If you are a beginning
programmer and aren't sure what functions to use, we suggest that you
concentrate on the formatted input functions (see Formatted Input.)
and formatted output functions (see Formatted Output.).

   If you are concerned about portability of your programs to systems
other than GNU, you should also be aware that file descriptors are not
as portable as streams.  You can expect any system running ANSI C to
support streams, but non-GNU systems may not support file descriptors at
all, or may only implement a subset of the GNU functions that operate on
file descriptors.  Most of the file descriptor functions in the GNU
library are included in the POSIX.1 standard, however.

File Position
-------------

   One of the attributes of an open file is its "file position" that
keeps track of where in the file the next character is to be read or
written.  In the GNU system, and all POSIX.1 systems, the file position
is simply an integer representing the number of bytes from the beginning
of the file.

   The file position is normally set to the beginning of the file when
it is opened, and each time a character is read or written, the file
position is incremented.  In other words, access to the file is normally
"sequential".

   Ordinary files permit read or write operations at any position within
the file.  Some other kinds of files may also permit this.  Files which
do permit this are sometimes referred to as "random-access" files.  You
can change the file position using the `fseek' function on a stream
(see File Positioning.) or the `lseek' function on a file
descriptor (see I/O Primitives.).  If you try to change the file
position on a file that doesn't support random access, you get the
`ESPIPE' error.

   Streams and descriptors that are opened for "append access" are
treated specially for output: output to such files is *always* appended
sequentially to the *end* of the file, regardless of the file position.
But, the file position is still used to control where in the file
reading is done.

   If you think about it, you'll realize that several programs can read
a given file at the same time.  In order for each program to be able to
read the file at its own pace, each program must have its own file
pointer, which is not affected by anything the other programs do.

   In fact, each opening of a file creates a separate file position.
Thus, if you open a file twice even in the same program, you get two
streams or descriptors with independent file positions.

   By contrast, if you open a descriptor and then duplicate it to get
another descriptor, these two descriptors share the same file position:
changing the file position of one descriptor will affect the other.

File Names
==========

   In order to open a connection to a file, or to perform other
operations such as deleting a file, you need some way to refer to the
file.  Nearly all files have names that are strings--even files which
are actually devices such as tape drives or terminals.  These strings
are called "file names".  You specify the file name to say which file
you want to open or operate on.

   This section describes the conventions for file names and how the
operating system works with them.

Directories
-----------

   In order to understand the syntax of file names, you need to
understand how the file system is organized into a hierarchy of
directories.

   A "directory" is a file that contains information to associate other
files with names; these associations are called "links" or "directory
entries".  Sometimes, people speak of "files in a directory", but in
reality, a directory only contains pointers to files, not the files
themselves.

   The name of a file contained in a directory entry is called a "file
name component".  In general, a file name consists of a sequence of one
or more such components, separated by the slash character (`/').  A
file name which is just one component names a file with respect to its
directory.  A file name with multiple components names a directory, and
then a file in that directory, and so on.

   Some other documents, such as the POSIX standard, use the term
"pathname" for what we call a file name, and either "filename" or
"pathname component" for what this manual calls a file name component.
We don't use this terminology because a "path" is something completely
different (a list of directories to search), and we think that
"pathname" used for something else will confuse users.  We always use
"file name" and "file name component" (or sometimes just "component",
where the context is obvious) in GNU documentation.

   You can find more detailed information about operations on
directories in File System Interface.

File Name Resolution
--------------------

   A file name consists of file name components separated by slash
(`/') characters.  On the systems that the GNU C library supports,
multiple successive `/' characters are equivalent to a single `/'
character.

   The process of determining what file a file name refers to is called
"file name resolution".  This is performed by examining the components
that make up a file name in left-to-right order, and locating each
successive component in the directory named by the previous component.
Of course, each of the files that are referenced as directories must
actually exist, be directories instead of regular files, and have the
appropriate permissions to be accessible by the process; otherwise the
file name resolution fails.

   If a file name begins with a `/', the first component in the file
name is located in the "root directory" of the process (usually all
processes on the system have the same root directory).  Such a file name
is called an "absolute file name".

   Otherwise, the first component in the file name is located in the
current working directory (see Working Directory.).  This kind of
file name is called a "relative file name".

   The file name components `.' ("dot") and `..' ("dot-dot") have
special meanings.  Every directory has entries for these file name
components.  The file name component `.' refers to the directory
itself, while the file name component `..' refers to its "parent
directory" (the directory that contains the link for the directory in
question).  As a special case, `..' in the root directory refers to the
root directory itself, since it has no parent; thus `/..' is the same
as `/'.

   Here are some examples of file names:

`/a'
     The file named `a', in the root directory.

`/a/b'
     The file named `b', in the directory named `a' in the root
     directory.

`a'
     The file named `a', in the current working directory.

`/a/./b'
     This is the same as `/a/b'.

`./a'
     The file named `a', in the current working directory.

`../a'
     The file named `a', in the parent directory of the current working
     directory.

   A file name that names a directory may optionally end in a `/'.  You
can specify a file name of `/' to refer to the root directory, but the
empty string is not a meaningful file name.  If you want to refer to
the current working directory, use a file name of `.' or `./'.

   Unlike some other operating systems, the GNU system doesn't have any
built-in support for file types (or extensions) or file versions as part
of its file name syntax.  Many programs and utilities use conventions
for file names--for example, files containing C source code usually
have names suffixed with `.c'--but there is nothing in the file system
itself that enforces this kind of convention.

File Name Errors
----------------

   Functions that accept file name arguments usually detect these
`errno' error conditions relating to file name syntax.  These errors
are referred to throughout this manual as the "usual file name syntax
errors".

`EACCES'
     The process does not have search permission for a directory
     component of the file name.

`ENAMETOOLONG'
     This error is used when either the the total length of a file name
     is greater than `PATH_MAX', or when an individual file name
     component has a length greater than `NAME_MAX'.  See Limits for Files.

     In the GNU system, there is no imposed limit on overall file name
     length, but some file systems may place limits on the length of a
     component.

`ENOENT'
     This error is reported when a file referenced as a directory
     component in the file name doesn't exist, or when a component is a
     symbolic link whose target file does not exist.  See Symbolic Links.

`ENOTDIR'
     A file that is referenced as a directory component in the file name
     exists, but it isn't a directory.

`ELOOP'
     Too many symbolic links were resolved while trying to look up the
     file name.  The system has an arbitrary limit on the number of
     symbolic links that may be resolved in looking up a single file
     name, as a primitive way to detect loops.  See Symbolic Links.

Portability of File Names
-------------------------

   The rules for the syntax of file names discussed in File Names,
are the rules normally used by the GNU system and by other
POSIX systems.  However, other operating systems may use other
conventions.

   There are two reasons why it can be important for you to be aware of
file name portability issues:

   * If your program makes assumptions about file name syntax, or
     contains embedded literal file name strings, it is more difficult
     to get it to run under other operating systems that use different
     syntax conventions.

   * Even if you are not concerned about running your program on
     machines that run other operating systems, it may still be
     possible to access files that use different naming conventions.
     For example, you may be able to access file systems on another
     computer running a different operating system over a network, or
     read and write disks in formats used by other operating systems.

   The ANSI C standard says very little about file name syntax, only
that file names are strings.  In addition to varying restrictions on the
length of file names and what characters can validly appear in a file
name, different operating systems use different conventions and syntax
for concepts such as structured directories and file types or
extensions.  Some concepts such as file versions might be supported in
some operating systems and not by others.

   The POSIX.1 standard allows implementations to put additional
restrictions on file name syntax, concerning what characters are
permitted in file names and on the length of file name and file name
component strings.  However, in the GNU system, you do not need to worry
about these restrictions; any character except the null character is
permitted in a file name string, and there are no limits on the length
of file name strings.

Input/Output on Streams
***********************

   This chapter describes the functions for creating streams and
performing input and output operations on them.  As discussed in
I/O Overview, a stream is a fairly abstract, high-level concept
representing a communications channel to a file, device, or process.

Streams
=======

   For historical reasons, the type of the C data structure that
represents a stream is called `FILE' rather than "stream".  Since most
of the library functions deal with objects of type `FILE *', sometimes
the term "file pointer" is also used to mean "stream".  This leads to
unfortunate confusion over terminology in many books on C.  This
manual, however, is careful to use the terms "file" and "stream" only
in the technical sense.

   The `FILE' type is declared in the header file `stdio.h'.

 - Data Type: FILE
     This is the data type used to represent stream objects.  A `FILE'
     object holds all of the internal state information about the
     connection to the associated file, including such things as the
     file position indicator and buffering information.  Each stream
     also has error and end-of-file status indicators that can be
     tested with the `ferror' and `feof' functions; see EOF and Errors.

   `FILE' objects are allocated and managed internally by the
input/output library functions.  Don't try to create your own objects of
type `FILE'; let the library do it.  Your programs should deal only
with pointers to these objects (that is, `FILE *' values) rather than
the objects themselves.

Standard Streams
================

   When the `main' function of your program is invoked, it already has
three predefined streams open and available for use.  These represent
the "standard" input and output channels that have been established for
the process.

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

 - Variable: FILE * stdin
     The "standard input" stream, which is the normal source of input
     for the program.

 - Variable: FILE * stdout
     The "standard output" stream, which is used for normal output from
     the program.

 - Variable: FILE * stderr
     The "standard error" stream, which is used for error messages and
     diagnostics issued by the program.

   In the GNU system, you can specify what files or processes
correspond to these streams using the pipe and redirection facilities
provided by the shell.  (The primitives shells use to implement these
facilities are described in File System Interface.)  Most other
operating systems provide similar mechanisms, but the details of how to
use them can vary.

   In the GNU C library, `stdin', `stdout', and `stderr' are normal
variables which you can set just like any others.  For example, to
redirect the standard output to a file, you could do:

     fclose (stdout);
     stdout = fopen ("standard-output-file", "w");

   Note however, that in other systems `stdin', `stdout', and `stderr'
are macros that you cannot assign to in the normal way.  But you can
use `freopen' to get the effect of closing one and reopening it.  See
Opening Streams.

Opening Streams
===============

   Opening a file with the `fopen' function creates a new stream and
establishes a connection between the stream and a file.  This may
involve creating a new file.

   Everything described in this section is declared in the header file
`stdio.h'.

 - Function: FILE * fopen (const char *FILENAME, const char *OPENTYPE)
     The `fopen' function opens a stream for I/O to the file FILENAME,
     and returns a pointer to the stream.

     The OPENTYPE argument is a string that controls how the file is
     opened and specifies attributes of the resulting stream.  It must
     begin with one of the following sequences of characters:

    `r'
          Open an existing file for reading only.

    `w'
          Open the file for writing only.  If the file already exists,
          it is truncated to zero length.  Otherwise a new file is
          created.

    `a'
          Open a file for append access; that is, writing at the end of
          file only.  If the file already exists, its initial contents
          are unchanged and output to the stream is appended to the end
          of the file.  Otherwise, a new, empty file is created.

    `r+'
          Open an existing file for both reading and writing.  The
          initial contents of the file are unchanged and the initial
          file position is at the beginning of the file.

    `w+'
          Open a file for both reading and writing.  If the file
          already exists, it is truncated to zero length.  Otherwise, a
          new file is created.

    `a+'
          Open or create file for both reading and appending.  If the
          file exists, its initial contents are unchanged.  Otherwise,
          a new file is created.  The initial file position for reading
          is at the beginning of the file, but output is always
          appended to the end of the file.

     As you can see, `+' requests a stream that can do both input and
     output.  The ANSI standard says that when using such a stream, you
     must call `fflush' (see Stream Buffering.) or a file
     positioning function such as `fseek' (see File Positioning.)
     when switching from reading to writing or vice versa.  Otherwise,
     internal buffers might not be emptied properly.  The GNU C library
     does not have this limitation; you can do arbitrary reading and
     writing operations on a stream in whatever order.

     The GNU C library defines one additional character for use in
     OPENTYPE: the character `x' insists on creating a new file--if a
     file FILENAME already exists, `fopen' fails rather than opening
     it.  If you use `x' you can are guaranteed that you will not
     clobber an existing file.  This is equivalent to the `O_EXCL'
     option to the `open' function (see Opening and Closing Files.).

     The character `b' in OPENTYPE has a standard meaning; it requests
     a binary stream rather than a text stream.  But this makes no
     difference in POSIX systems (including the GNU system).  If both
     `+' and `b' are specified, they can appear in either order.  See
     Binary Streams.

     Any other characters in OPENTYPE are simply ignored.  They may be
     meaningful in other systems.

     If the open fails, `fopen' returns a null pointer.

   You can have multiple streams (or file descriptors) pointing to the
same file open at the same time.  If you do only input, this works
straightforwardly, but you must be careful if any output streams are
included.  See Stream/Descriptor Precautions.  This is equally true
whether the streams are in one program (not usual) or in several
programs (which can easily happen).  It may be advantageous to use the
file locking facilities to avoid simultaneous access.  See File Locks.

 - Macro: int FOPEN_MAX
     The value of this macro is an integer constant expression that
     represents the minimum number of streams that the implementation
     guarantees can be open simultaneously.  You might be able to open
     more than this many streams, but that is not guaranteed.  The
     value of this constant is at least eight, which includes the three
     standard streams `stdin', `stdout', and `stderr'.  In POSIX.1
     systems this value is determined by the `OPEN_MAX' parameter;
     see General Limits..  In BSD and GNU, it is controlled by the
     `RLIMIT_NOFILE' resource limit; see Limits on Resources..

 - Function: FILE * freopen (const char *FILENAME, const char
          *OPENTYPE, FILE *STREAM)
     This function is like a combination of `fclose' and `fopen'.  It
     first closes the stream referred to by STREAM, ignoring any errors
     that are detected in the process.  (Because errors are ignored,
     you should not use `freopen' on an output stream if you have
     actually done any output using the stream.)  Then the file named by
     FILENAME is opened with mode OPENTYPE as for `fopen', and
     associated with the same stream object STREAM.

     If the operation fails, a null pointer is returned; otherwise,
     `freopen' returns STREAM.

     `freopen' has traditionally been used to connect a standard stream
     such as `stdin' with a file of your own choice.  This is useful in
     programs in which use of a standard stream for certain purposes is
     hard-coded.  In the GNU C library, you can simply close the
     standard streams and open new ones with `fopen'.  But other
     systems lack this ability, so using `freopen' is more portable.

Closing Streams
===============

   When a stream is closed with `fclose', the connection between the
stream and the file is cancelled.  After you have closed a stream, you
cannot perform any additional operations on it.

 - Function: int fclose (FILE *STREAM)
     This function causes STREAM to be closed and the connection to the
     corresponding file to be broken.  Any buffered output is written
     and any buffered input is discarded.  The `fclose' function returns
     a value of `0' if the file was closed successfully, and `EOF' if
     an error was detected.

     It is important to check for errors when you call `fclose' to close
     an output stream, because real, everyday errors can be detected at
     this time.  For example, when `fclose' writes the remaining
     buffered output, it might get an error because the disk is full.
     Even if you know the buffer is empty, errors can still occur when
     closing a file if you are using NFS.

     The function `fclose' is declared in `stdio.h'.

   If the `main' function to your program returns, or if you call the
`exit' function (see Normal Termination.), all open streams are
automatically closed properly.  If your program terminates in any other
manner, such as by calling the `abort' function (see Aborting a Program.)
or from a fatal signal (see Signal Handling.), open
streams might not be closed properly.  Buffered output might not be
flushed and files may be incomplete.  For more information on buffering
of streams, see Stream Buffering.

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

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

   These functions are declared in the header file `stdio.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: 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.  `putc' is usually
     the best function to use for writing a single character.

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

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

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

          puts ("This is a message.");

 - 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 (see Block Input/Output.).

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

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

 - 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: 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: int getchar (void)
     The `getchar' function is equivalent to `getc' with `stdin' as the
     value of the STREAM argument.

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

     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 = 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 (see Block Input/Output.).

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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