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

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

Incomplete:  RMS suggests that a short example might be useful here.

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 is 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 End-Of-File 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 some 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.

 -- Macro: FILE * stdin
     This macro expands into an expression that represents the standard input stream, the normal source of input for the program.

 -- Macro: FILE * stdout
     This macro expands into an expression that represents the standard output stream, the destination for normal output from the program.

 -- Macro: FILE * stderr
     This macro expands into an expression that represents the standard error stream, the destination for error and diagnostic messages 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.

It is probably not a good idea to close any of the standard 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.

The functions in this section are declared in the header file stdio.h.

 -- Function: FILE * fopen (const char *FILENAME, const char *OPENTYPE)
     The fopen function opens the file named by the string FILENAME, and returns a pointer to a stream that is associated with it.

     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 existing file for reading only.

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

     "a"
          Open 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 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 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 might be at either the beginning or end of the file, but output is always appended to the end of the file.

     Any of the above sequences can also be followed by a character b to indicate that a binary (rather than text) stream should be created; see Text and Binary Streams.  If both + and b are specified, they can appear in either order.  For example, "r+b" and "rb+" are equivalent; they both specify an existing binary file being opened for both read and write access.  In GNU and other POSIX systems, `b' has no effect since there is no difference between text and binary streams.

     When a file is opened with the + option for both reading and writing, you must call either fflush (see Stream Buffering) or a file positioning function such as fseek (see File Positioning) when switching back and forth between read and write operations.  Otherwise, internal buffers might not be emptied properly.

     Additional characters that follow these sequences specify other implementation-specific file or stream attributes.

     The GNU C library defines only one additional attribute: if the character x is given, this specifies exclusive use of a new file. This is equivalent to the O_EXCL option to the open function (see File Status Flags).  Any other characters are simply ignored.

     Other systems may define other character sequences to specify things like a record size or access control specification.

     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 fine, but you can get unpredictable results if you are writing to the file.  It is unusual to have more than one stream open for a given file in one program, but not unusual for several programs (or at least several instances of one program) to open the same file.  In such cases, your programs should 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.  The value of this constant is at least eight, which includes the three standard streams stdin, stdout, and stderr.

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

     The main use of freopen is to connect a standard stream such as stdir 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.

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

 -- 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 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 Program 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 may not be flushed and files may not be complete.  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.  Largely for historical compatibility, there are several variants of these functions, but as a matter of style (and for simplicity!) we suggest you stick with using fputc and fputs, and perhaps putc and putchar.

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.

     In the GNU library, fputc also has a definition as a macro, which is just as fast but computes its arguments only once.  So there is no reason to prefer putc with the GNU library.

 -- Function: int putchar (int C)
     The putchar function is equivalent to fputc 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.

 -- 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.  Again, there are several variants of these functions, some of which are considered obsolete stylistically.  It's suggested that you stick with fgetc, getline, and maybe getc, getchar and fgets.

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.

 -- Function: int getchar (void)
     The getchar function is equivalent to fgetc 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 delimeter 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 is *LINEPTR.

     Before calling getline, you should place in *LINEPTR the address of a buffer *N bytes long.  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.

     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 DELIMETER specifies the delimeter character; getdelim keeps reading until it sees that character (or end of file).

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

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

     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.

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.

Using ungetc To Do Unreading
----------------------------

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

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

     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 or rewind; see 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.  Reading that character will set the end-of-file indicator again.

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>

     void
     skip_whitespace (FILE *stream)
     {
       int c;
       do {
         c = getc (stream);
         if (c == EOF) return;
       } while (isspace (c));
       ungetc (c, stream);
     }

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.

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 modifier between the % and the character that indicates which conversion to apply.  These alter slightly 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.

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 (see Extended Characters) are permitted in a template string.

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

     % 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:

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

     The GNU library's version of printf also allows you to 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.  Other C library versions may not recognize this syntax.

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

     The GNU library's version of printf also allows you to 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.  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.

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

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

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

%o
     Print an integer as an unsigned octal number.  See Integer Conversions, for details.

%u
     Print an integer as an unsigned decimal number.  See Integer Conversions, for details.

%x, %X
     Print an integer as an unsigned hexadecimal number.  %x uses lower-case letters and %X uses upper-case.  See Integer Conversions, for details.

%f
     Print a floating-point number in normal (fixed-point) notation. See Floating-Point Conversions, for details.

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

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

%c
     Print a single character.  See Other Output Conversions.

%s
     Print a string.  See Other Output Conversions.

%p
     Print the value of a pointer.  See Other Output Conversions.

%n
     Get the number of characters printed so far.  See Other Output Conversions.

%%
     Print a literal % character.  See Other Output Conversions.

Incomplete: There also seems to be a Z conversion for printing a size_t value in decimal notation.  Is this something we want to publicize?

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

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

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

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

The following flags are meaningful:

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

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

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

#
     For the %o conversion, this forces the leading digit to be 0, as if by increasing the precision.  For %x or %X, this prefixes a leading 0x or 0X (respectively) to the result. This doesn't do anything useful for the %d, %i, or %u conversions.

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

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

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

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

l
     Specifies that the argument is a long int or unsigned long int, as appropriate.

L
     Specifies that the argument is a long long int.  (This type is an extension supported by the GNU C compiler.  On systems that don't support extra-long integers, this is the same as long int.)

For example, using the template string:

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

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

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

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

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

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

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

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

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

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

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

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

The following flags can be used to modify the behavior:

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

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

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

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

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

The precision specifies how many digits follow the decimal-point character for the %f, %e, and %E conversions.  For these conversions, the default is 6.  If the precision is explicitly 0, this has the rather strange effect of suppressing the decimal point character entirely!  For the %g and %G conversions, the precision specifies how many significant digits to print; if 0 or not specified, it is treated like a value of 1.

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

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

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

     "|%12.4f|%12.4e|%12.4g|\n"

Here is the output:

     |      0.0000|  0.0000e+00|           0|
     |      1.0000|  1.0000e+00|           1|
     |     -1.0000| -1.0000e+00|          -1|
     |    100.0000|  1.0000e+02|         100|
     |   1000.0000|  1.0000e+03|        1000|
     |  10000.0000|  1.0000e+04|       1e+04|
     |  12345.0000|  1.2345e+04|   1.234e+04|
     | 100000.0000|  1.0000e+05|       1e+05|
     | 123456.0000|  1.2346e+05|   1.234e+05|

Notice how the %g conversion drops trailing zeros.

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

This section describes miscellaneous conversions for printf.

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

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

prints hello.

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

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

prints  nowhere .

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

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

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

For example:

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

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

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

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

For example,

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

prints:

     3 bears

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

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

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

This section describes how to call printf and related functions. Prototypes for these functions are in the header file stdio.h.

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

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

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

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

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

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

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

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

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

          /* Print a message describing the value of a variable
             whose name is NAME and whose value is VALUE. */
          char *
          make_message (char *name, char *value)
          {
            /* Guess we need no more than 100 chars of space. */
            int size = 100;
            char *buffer = (char *) xmalloc (size);
            while (1) {
              /* Try to print in the allocated space. */
              int nchars = snprintf (buffer, size,
                                     "value of %s is %s", name, value);
              /* If that worked, return the string. */
              if (nchars < size)
                return buffer;
              /* Else try again with twice as much space. */
              size *= 2;
              buffer = (char *) xrealloc (size, buffer);
            }
          }

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

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

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

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

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

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

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

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

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

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

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

The GNU library does not have such restrictions.  You can safely continue to fetch arguments from a va_list pointer after passing it to vprintf, and va_end is a no-op.

Prototypes for these functions are declared in stdio.h.

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

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

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

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

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

Here's an example showing how you might use vfprintf.  This is a function that prints error messages to the stream stderr, along with a prefix indicating the name of the program.

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

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

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

You could call eprintf like this:

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

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

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

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

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

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

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

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

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

 -- Macro: int PA_INT
     This specifies that the base type is int.

 -- Macro: int PA_CHAR
     This specifies that the base type is int, cast to char.

 -- Macro: int PA_STRING
     This specifies that the base type is char *, a null-terminated string.

 -- Macro: int PA_POINTER
     This specifies that the base type is void *, an arbitrary pointer.

 -- Macro: int PA_FLOAT
     This specifies that the base type is float.

 -- Macro: int PA_DOUBLE
     This specifies that the base type is double.

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

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

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

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

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

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

 -- Macro: int PA_FLAG_LONGLONG
     If this bit is set, it indicates that the base type is modified with long long.  (This corresponds to the L type modifier.)

 -- Macro: int PA_FLAG_LONGDOUBLE
     This is a synonym for PA_FLAG_LONGLONG, used by convention with a base type of PA_DOUBLE to indicate a type of long double.

Incomplete: Should have an example here from a fictional interpreter, showing how one might validate a list of args and then call vprintf.

Customizing Printf
==================

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

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

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

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

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

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

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

 -- Function: int register_printf_function (int SPEC, printf_function HANDLER_FUNCTION, printf_arginfo_function ARGINFO_FUNCTION)
     This function defines the conversion specifier character SPEC. Thus, if SPEC is 'q', it defines the conversion %q.

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

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

     Normally, you install both functions for a conversion at the same time, but if you are never going to call parse_printf_format, you do not need to define an arginfo function.

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

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

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

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

Both the HANDLER_FUNCTION and ARGINFO_FUNCTION arguments to register_printf_function accept an argument of type struct print_info, which contains information about the options appearing in an instance of the conversion specifier.  This data type is declared in the header file printf.h.

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

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

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

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

     unsigned int is_long_double
          This is a boolean that is true if the L type modifier was specified.

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

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

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

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

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

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

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

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

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

You should define your handler functions with a prototype like:

     int FUNCTION (FILE *stream, const struct printf_info *info,
                         va_list *ap_pointer)

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

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

The ap_pointer argument is used to pass the tail of the variable argument list containing the values to be printed to your handler. Unlike most other functions that can be passed an explicit variable argument list, this is a pointer to a va_list, rather than the va_list itself.  Thus, you should fetch arguments by means of va_arg (TYPE, *ap_pointer).

(Passing a pointer here allows the function that calls your handler function to update its own va_list variable to account for the arguments that your handler processes.  See Variable Argument Facilities.)

The return value from your handler function should be the number of argument values that it processes from the variable argument list.  You can also return a value of -1 to indicate an error.

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

If you are going to use parse_printf_format in your application, you should also define a function to pass as the ARGINFO_FUNCTION argument for each new conversion you install with register_printf_function.

You should define these functions with a prototype like:

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

The return value from the function should be the number of arguments the conversion expects, up to a maximum of N.  The function should also fill in the ARGTYPES array with information about the types of each of these arguments.  This information is encoded using the various PA_ macros.

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

Printf Extension Example
------------------------

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

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

     struct widget
     {
       char *name;
       ...
     };

     int
     print_widget (FILE *stream, const struct printf_info *info,
                   va_list *app)
     {
       struct widget *w;
       char *buffer;
       int padding_amount, i;

       /* Fetch the widget to be printed. */
       w = va_arg (*app, struct widget *);
       /* Format the output into a string. */
       padding_amount
         = (info->width -
            asprintf (&buffer, "<Widget %p: %s>", w, w->name));

       /* Pad to the minimum field width and print to the stream. */
       if (!info->left)
         for (i = 0; i < padding_amount; i++) fputc (' ', stream);
       fputs (buffer, stream);
       if (info->left)
         for (i = 0; i < padding_amount; i++) fputc (' ', stream);

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

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

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

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

The output produced by this program looks like:

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

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

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

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

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

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

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

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

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

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

If you are trying to read input that doesn't match a single, fixed pattern, you may be better off using a tool such as Bison to generate a parser, rather than using scanf.  For more information about this, see The Bison Reference Manual.

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

A scanf template string is a string that contains ordinary multibyte characters and conversion specifications introduced by a % character.

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

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

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

     % FLAGS WIDTH TYPE CONVERSION

More specifically, input conversion specifications consist of an initial % character followed in sequence by:

  * An optional flag character *, which causes assignment to be suppressed.  If this flag appears, input is read from the stream and matched against the conversion specification in the usual way, but no optional pointer argument is used, no assignment takes place, and the count of successful assignments is not incremented.

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

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

  * A character that specifies the conversion to be applied.

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

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

Here is a table that summarizes the various conversion specifications:

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

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

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

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

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

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

%s
     Matches a string of non-whitespace characters.  See String Input Conversions.

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

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

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

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

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

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

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

This section describes the scanf conversions for reading numeric values.

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

The %i conversion matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant.  The syntax that is recognized is the same as that for the strtol function (see Parsing of Integers) with the value 0 for the BASE argument.

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

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

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

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

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

l
     Specifies that the argument is a long int * or unsigned long int *.

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

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

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

l
     Specifies that the argument is of type double *.

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

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

This section describes the scanf input conversions for reading string and character values: %s, %[, and %c. The corresponding argument for all of these conversions should be of type char *.

Warning: the argument points to an array of characters where the input is stored.  To make a robust program, you must make sure that the input (including terminating null) cannot possibly exceed the size of this array.  In general, the only way to do this is to specify a maximum field width equal to the size you have allocated (minus one, to leave room for the terminating null).  Always specify a field width to limit the number of characters read.

The %c conversion is the simplest.  It matches a fixed-sized string of characters.  The number of characters read is controlled by the maximum field width.  If you don't supply a field width, then only one character is read.  Note that this conversion doesn't append a null character to the end of the string it reads.  It also does not skip over initial whitespace characters.

The %s conversion matches a string of non-whitespace characters. Unlike %c, this conversion does skip over initial whitespace and does mark the end of the string with a null character.

Warning: If you do not specify a field width for %s, then the number of characters read is limited only by where the next whitespace character appears.  This almost certainly means your program will crash if given invalid input.

For example, reading the input:

      hello, world

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

The %s conversion effectively reads in characters that belong to the set of non-whitespace characters.  To read in characters that belong to an arbitrary set, you can use the %[ conversion.  The characters which make up the set are specified immediately following the [ character, up to a matching ] character.  As special cases:

  * If a caret character ^ immediately follows the initial [, then the set that is used for matching is the complement of the set of characters that are explicitly listed.

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

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

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

Here are some examples of %[ conversions and what they mean.

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

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

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

%[a-z]
     Matches a string of lowercase characters.

One more reminder: the %s and %[ conversions are potentially dangerous if you don't specify a maximum width, because input too long would overflow whatever buffer you have provided for it.  No matter how long your buffer is, a user could supply input that is longer.  Don't assume that the input will be short enough to fit; a well-written program reports invalid input with a comprehensible error message, not with a crash.

So make your programs clean---always specify a maximum field width with the %s and %[ conversions.  Then you will probably get a matching error instead if the input string is too long, and you can detect this and report it properly.

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 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 Functions, 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 Variable Argument Facilities).

 -- 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 the number of objects actually written, which is less than COUNT only if a write error occurs.

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 Input/Output.

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 and Closing 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 Text and 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.

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 Input/Output.

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.

  * When the program terminates by calling exit.

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

  * Whenever an input operation on any stream actually reads data from the 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.

     The argument OPENTYPE is the same as in fopen (see Opening and Closing 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";

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

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

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

Here is an example of using open_memstream:

     #include <stdio.h>

     void
     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);
     }

This program produces the following output:

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

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

These facilities are declared in stdio.h.

 -- Data Type: __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:

     __io_read *__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.

     __io_write *__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.

     __io_seek *__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.

     __io_close *__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, __io_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 and Closing Streams.  (But note that the ``truncate on open'' option is ignored.)

     Incomplete: What is the default buffering mode for the newly created stream?

     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:

     int FUNCTION (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.  You can return a value of -1 to indicate an error.  You should define the function to write data to the cookie as:

     int FUNCTION (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 FUNCTION (void *COOKIE, fpos_t *POSITION, int WHENCE)

For this function, the position and whence arguments are interpreted as for fgetpos; see Text and Binary Streams. Remember that in the GNU system, 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 FUNCTION (void *COOKIE)

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

 -- Data Type: __io_read
     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: __io_write
     The data type of the write function for a custom stream.

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

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

Incomplete:  This section could use an example.