@node Input/Output on Streams @chapter Input/Output on Streams This chapter describes the functions for creating streams and performing input and output operations on them. As discussed in @ref{Input/Output Overview}, a stream is a fairly abstract, high-level concept representing a communications channel to a file, device, or process. @strong{Incomplete:} RMS suggests that a short example might be useful here. @menu * Streams:: About the data type representing a stream. * Standard Streams:: Streams to the standard input and output devices are created for you. * Opening Streams:: How to create a stream to talk to a file. * Closing Streams:: Close a stream when you are finished with it. * Simple Output:: Unformatted output by characters and lines. * Character Input:: Unformatted input by characters and words. * Line Input:: Reading a line or a record from a stream. * Unreading:: Peeking ahead/pushing back input just read. * Formatted Output:: @code{printf} and related functions. * Customizing Printf:: You can define new conversion specifiers for @code{printf} and friends. * Formatted Input:: @code{scanf} and related functions. * Block Input/Output:: Input and output operations on blocks of data. * EOF and Errors:: How you can tell if an I/O error happens. * Binary Streams:: Some systems distinguish between text files and binary files. * File Positioning:: About random-access streams. * Portable Positioning::Random access on peculiar ANSI C systems. * Stream Buffering:: How to control buffering of streams. * Temporary Files:: How to open a temporary file. * Other Streams:: How you can open additional kinds of streams, including streams that store data in a string, and your own custom streams. @end menu @node Streams @section Streams For historical reasons, the type of the C data structure that represents a stream is called @code{FILE} rather than ``stream''. Since most of the library functions deal with objects of type @code{FILE *}, sometimes the term @dfn{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. @cindex file pointer The @code{FILE} type is declared in the header file @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftp {Data Type} FILE This is the data type is used to represent stream objects. A @code{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 @code{ferror} and @code{feof} functions; see @ref{End-Of-File and Errors}. @end deftp @code{FILE} objects are allocated and managed internally by the input/output library functions. Don't try to create your own objects of type @code{FILE}; let the library do it. Your programs should deal only with pointers to these objects (that is, @code{FILE *} values) rather than the objects themselves. @node Standard Streams @section Standard Streams @cindex standard streams @cindex streams, standard When the @code{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 @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypevr Macro {FILE *} stdin This macro expands into an expression that represents the @dfn{standard input} stream, the normal source of input for the program. @end deftypevr @cindex standard input stream @comment stdio.h @comment ANSI @deftypevr Macro {FILE *} stdout This macro expands into an expression that represents the @dfn{standard output} stream, the destination for normal output from the program. @end deftypevr @cindex standard output stream @comment stdio.h @comment ANSI @deftypevr Macro {FILE *} stderr This macro expands into an expression that represents the @dfn{standard error} stream, the destination for error and diagnostic messages issued by the program. @end deftypevr @cindex standard error stream 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 @ref{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. @node Opening Streams @section Opening Streams @cindex opening a stream Opening a file with the @code{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 @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypefun {FILE *} fopen (const char *@var{filename}, const char *@var{opentype}) The @code{fopen} function opens the file named by the string @var{filename}, and returns a pointer to a stream that is associated with it. The @var{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: @table @code @item "r" Open existing file for reading only. @item "w" Open file for writing only. If the file already exists, it is truncated to zero length. Otherwise a new file is created. @item "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. @item "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. @item "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. @item "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. @end table Any of the above sequences can also be followed by a character @samp{b} to indicate that a binary (rather than text) stream should be created; see @ref{Text and Binary Streams}. If both @samp{+} and @samp{b} are specified, they can appear in either order. For example, @code{"r+b"} and @code{"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 @samp{+} option for both reading and writing, you must call either @code{fflush} (@pxref{Stream Buffering}) or a file positioning function such as @code{fseek} (@pxref{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 @samp{x} is given, this specifies exclusive use of a new file. This is equivalent to the @code{O_EXCL} option to the @code{open} function (@pxref{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, @code{fopen} returns a null pointer. @end deftypefun 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. @xref{File Locks}. @comment stdio.h @comment ANSI @deftypevr 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 @code{stdin}, @code{stdout}, and @code{stderr}. @end deftypevr @comment stdio.h @comment ANSI @deftypefun {FILE *} freopen (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream}) This function is like a combination of @code{fclose} and @code{fopen}. It first closes the stream referred to by @var{stream}, ignoring any errors that are detected in the process. (Because errors are ignored, you should not use @code{freopen} on an output stream if you have actually done any output using the stream.) Then the file named by @var{filename} is opened with mode @var{opentype} as for @code{fopen}, and associated with the same stream object @var{stream}. If the operation fails, a null pointer is returned; otherwise, @code{freopen} returns @var{stream}. The main use of @code{freopen} is to connect a standard stream such as @code{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. @end deftypefun @node Closing Streams @section Closing Streams @cindex closing a stream When a stream is closed with @code{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. @comment stdio.h @comment ANSI @deftypefun int fclose (FILE *@var{stream}) This function causes @var{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 @code{fclose} function returns a value of @code{0} if the file was closed successfully, and @code{EOF} if an error was detected. It is important to check for errors when you call @code{fclose} to close an output stream, because real, everyday errors can be detected at this time. For example, when @code{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 @code{fclose} is declared in @file{stdio.h}. @end deftypefun If the @code{main} function to your program returns, or if you call the @code{exit} function (@pxref{Normal Program Termination}), all open streams are automatically closed properly. If your program terminates in any other manner, such as by calling the @code{abort} function (@pxref{Aborting a Program}) or from a fatal signal (@pxref{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 @ref{Stream Buffering}. @node Simple Output @section Simple Output by Characters or Lines @cindex writing to a stream, by characters 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 @code{fputc} and @code{fputs}, and perhaps @code{putc} and @code{putchar}. These functions are declared in the header file @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypefun int fputc (int @var{c}, FILE *@var{stream}) The @code{fputc} function converts the character @var{c} to type @code{unsigned char}, and writes it to the stream @var{stream}. @code{EOF} is returned if a write error occurs; otherwise the character @var{c} is returned. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int putc (int @var{c}, FILE *@var{stream}) This is just like @code{fputc}, except that most systems implement it as a macro, making it faster. One consequence is that it may evaluate the @var{stream} argument more than once. In the GNU library, @code{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 @code{putc} with the GNU library. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int putchar (int @var{c}) The @code{putchar} function is equivalent to @code{fputc} with @code{stdout} as the value of the @var{stream} argument. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int fputs (const char *@var{s}, FILE *@var{stream}) The function @code{fputs} writes the string @var{s} to the stream @var{stream}. The terminating null character is not written. This function does @emph{not} add a newline character, either. It outputs only the chars in the string. This function returns @code{EOF} if a write error occurs, and otherwise a non-negative value. For example: @example fputs ("Are ", stdout); fputs ("you ", stdout); fputs ("hungry?\n", stdout); @end example @noindent outputs the text @samp{Are you hungry?} followed by a newline. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int puts (const char *@var{s}) The @code{puts} function writes the string @var{s} to the stream @code{stdout} followed by a newline. The terminating null character of the string is not written. @end deftypefun @comment stdio.h @comment SVID @deftypefun int putw (int @var{w}, FILE *@var{stream}) This function writes the word @var{w} (that is, an @code{int}) to @var{stream}. It is provided for compatibility with SVID, but we recommend you use @code{fwrite} instead (@pxref{Block Input/Output}). @end deftypefun @node Character Input @section Character Input @cindex reading from a stream, by characters 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 @code{fgetc}, @code{getline}, and maybe @code{getc}, @code{getchar} and @code{fgets}. These functions are declared in the header file @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypefun int fgetc (FILE *@var{stream}) This function reads the next character as an @code{unsigned char} from the stream @var{stream} and returns its value, converted to an @code{int}. If an end-of-file condition or read error occurs, @code{EOF} is returned instead. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int getc (FILE *@var{stream}) This is just like @code{fgetc}, except that it is permissible (and typical) for it to be implemented as a macro that evaluates the @var{stream} argument more than once. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int getchar (void) The @code{getchar} function is equivalent to @code{fgetc} with @code{stdin} as the value of the @var{stream} argument. @end deftypefun Here is an example of a function that does input using @code{fgetc}. It would work just as well using @code{getc} instead, or using @code{getchar ()} instead of @code{fgetc (stdin)}. @example int y_or_n_p (const char *question) @{ fputs (question, stdout); while (1) @{ int c, answer; /* @r{Write a space to separate answer from question.} */ fputc (' ', stdout); /* @r{Read the first character of the line.} @r{This should be the answer character, but might not be.} */ c = tolower (fgetc (stdin)); answer = c; /* @r{Discard rest of input line.} */ while (c != '\n') c = fgetc (stdin); /* @r{Obey the answer if it was valid.} */ if (answer == 'y') return 1; if (answer == 'n') return 0; /* @r{Answer was invalid: ask for valid answer.} */ fputs ("Please answer y or n:", stdout); @} @} @end example @comment stdio.h @comment SVID @deftypefun int getw (FILE *@var{stream}) This function reads a word (that is, an @code{int}) from @var{stream}. It's provided for compatibility with SVID. We recommend you use @code{fread} instead (@pxref{Block Input/Output}). @end deftypefun @node Line Input @section 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 @code{gets}) long lines can confuse them. So the GNU library provides the nonstandard @code{getline} function that makes it easy to read lines reliably. Another GNU extension, @code{getdelim}, generalizes @code{getline}. It reads a delimited record, defined as everything through the next occurrence of a specified delimeter character. All these functions are declared in @file{stdio.h}. @comment stdio.h @comment GNU @deftypefun ssize_t getline (char **@var{lineptr}, size_t *@var{n}, FILE *@var{stream}) This function reads an entire line from @var{stream}, storing the text (including the newline and a terminating null character) in a buffer and storing the buffer address is @code{*@var{lineptr}}. Before calling @code{getline}, you should place in @code{*@var{lineptr}} the address of a buffer @code{*@var{n}} bytes long. If this buffer is long enough to hold the line, @code{getline} stores the line in this buffer. Otherwise, @code{getline} makes the buffer bigger using @code{realloc}, storing the new buffer address back in @code{*@var{lineptr}} and the increased size back in @code{*@var{n}}. In either case, when @code{getline} returns, @code{*@var{lineptr}} is a @code{char *} which points to the text of the line. When @code{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, @code{getline} returns @code{-1}. @end deftypefun @comment stdio.h @comment GNU @deftypefun ssize_t getdelim (char **@var{lineptr}, size_t *@var{n}, int @var{delimiter}, FILE *@var{stream}) This function is like @code{getline} except that the character which tells it to stop reading is not necessarily newline. The argument @var{delimeter} specifies the delimeter character; @code{getdelim} keeps reading until it sees that character (or end of file). The text is stored in @var{lineptr}, including the delimeter character and a terminating null. Like @code{getline}, @code{getline} makes @var{lineptr} bigger if it isn't big enough. @end deftypefun @comment stdio.h @comment ANSI @deftypefun {char *} fgets (char *@var{s}, int @var{count}, FILE *@var{stream}) The @code{fgets} function reads characters from the stream @var{stream} up to and including a newline character and stores them in the string @var{s}, adding a null character to mark the end of the string. You must supply @var{count} characters worth of space in @var{s}, but the number of characters read is at most @var{count} @minus{} 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 @code{fgets}, then the contents of the array @var{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 @var{s}. @strong{Warning:} If the input data has a null character, you can't tell. So don't use @code{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 @code{getline} instead of @code{fgets}. @end deftypefun @comment stdio.h @comment ANSI @deftypefn {Deprecated function} {char *} gets (char *@var{s}) The function @code{gets} reads characters from the stream @code{stdin} up to the next newline character, and stores them in the string @var{s}. The newline character is discarded (note that this differs from the behavior of @code{fgets}, which copies the newline character into the string). @strong{Warning:} The @code{gets} function is @strong{very dangerous} because it provides no protection against overflowing the string @var{s}. The GNU library includes it for compatibility only. You should @strong{always} use @code{fgets} or @code{getline} instead. @end deftypefn @node Unreading @section Unreading @cindex peeking at input @cindex unreading characters @cindex pushing input back 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 @dfn{unreading} it (also called @dfn{pushing it back} on the stream). Unreading a character makes it available to be input again from the stream, by the next call to @code{fgetc} or other input function on that stream. @menu * Unreading Idea:: An explanation of unreading with pictures. * How Unread:: How to call @code{ungetc} to do unreading. @end menu @node Unreading Idea @subsection 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 @samp{foobar}. Suppose you have read three characters so far. The situation looks like this: @example f o o b a r ^ @end example @noindent so the next input character will be @samp{b}. If instead of reading @samp{b} you unread the letter @samp{o}, you get a situation like this: @example f o o b a r | o-- ^ @end example @noindent so that the next input characters will be @samp{o} and @samp{b}. If you unread @samp{9} instead of @samp{o}, you get this situation: @example f o o b a r | 9-- ^ @end example @noindent so that the next input characters will be @samp{9} and @samp{b}. @node How Unread @subsection Using @code{ungetc} To Do Unreading The function to unread a character is called @code{ungetc}, because it reverses the action of @code{fgetc}. @comment stdio.h @comment ANSI @deftypefun int ungetc (int @var{c}, FILE *@var{stream}) The @code{ungetc} function pushes back the character @var{c} onto the input stream @var{stream}. So the next input from @var{stream} will read @var{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 @code{ungetc}! But that is a strange way to write a program; usually @code{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 @code{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 @code{fseek} or @code{rewind}; @pxref{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. @end deftypefun Here is an example showing the use of @code{getc} and @code{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. @example #include void skip_whitespace (FILE *stream) @{ int c; do @{ c = getc (stream); if (c == EOF) return; @} while (isspace (c)); ungetc (c, stream); @} @end example @node Formatted Output @section Formatted Output @cindex format string, for @code{printf} @cindex template, for @code{printf} @cindex formatted output to a stream @cindex writing to a stream, formatted The functions described in this section (@code{printf} and related functions) provide a convenient way to perform formatted output. You call @code{printf} with a @dfn{format string} or @dfn{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 @code{printf} or one of the other related functions described in this section is usually the easiest and most concise way to perform output. These functions are especially useful for printing error messages, tables of data, and the like. @menu * Formatted Output Basics:: Some examples to get you started. * Output Conversion Syntax:: General syntax of conversion specifications. * Table of Output Conversions:: Summary of output conversions and what they do. * Integer Conversions:: Details about formatting of integers. * Floating-Point Conversions:: Details about formatting of floating-point numbers. * Other Output Conversions:: Details about formatting of strings, characters, pointers, and the like. * Formatted Output Functions:: Descriptions of the actual functions. * Variable Arguments Output Functions:: @code{vprintf} and friends. * Parsing a Template String:: What kinds of args does a given template call for? @end menu @node Formatted Output Basics @subsection Formatted Output Basics The @code{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 @dfn{conversion specifications} introduced by a @samp{%} character in the template cause subsequent arguments to be formatted and written to the output stream. For example, @cindex conversion specifications (@code{printf}) @example int pct = 37; char filename[] = "foo.txt"; printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n", filename, pct); @end example @noindent produces output like @example Processing of `foo.txt' is 37% finished. Please be patient. @end example This example shows the use of the @samp{%d} conversion to specify that an @code{int} argument should be printed in decimal notation, the @samp{%s} conversion to specify printing of a string argument, and the @samp{%%} conversion to print a literal @samp{%} character. There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (@samp{%o}, @samp{%u}, or @samp{%x}, respectively); or as a character value (@samp{%c}). Floating-point numbers can be printed in normal, fixed-point notation using the @samp{%f} conversion or in exponential notation using the @samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e} or @samp{%f} format, depending on what is more appropriate for the magnitude of the particular number. You can control formatting more precisely by writing @dfn{modifier} between the @samp{%} 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. @node Output Conversion Syntax @subsection Output Conversion Syntax This section provides details about the precise syntax of conversion specifications that can appear in a @code{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 (@pxref{Extended Characters}) are permitted in a template string. The conversion specifications in a @code{printf} template string have the general form: @example % @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion} @end example For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-} is a flag, @samp{10} specifies the field width, the precision is @samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies the conversion style. (This particular type specifier says to print a @code{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 @samp{%} character followed in sequence by: @itemize @bullet @item Zero or more @dfn{flag characters} that modify the normal behavior of the conversion specification. @cindex flag character (@code{printf}) @item An optional decimal integer specifying the @dfn{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 @emph{minimum} value; if the normal conversion produces more characters than this, the field is @emph{not} truncated. Normally, the output is right-justified within the field. @cindex minimum field width (@code{printf}) The GNU library's version of @code{printf} also allows you to specify a field width of @samp{*}. 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 @code{int}. Other C library versions may not recognize this syntax. @item An optional @dfn{precision} to specify the number of digits to be written for the numeric conversions. If the precision is specified, it consists of a period (@samp{.}) followed optionally by a decimal integer (which defaults to zero if omitted). @cindex precision (@code{printf}) The GNU library's version of @code{printf} also allows you to specify a precision of @samp{*}. 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 @code{int}. If you specify @samp{*} for both the field width and precision, the field width argument precedes the precision argument. Other C library versions may not recognize this syntax. @item An optional @dfn{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 @code{int}, but you can specify @samp{h}, @samp{l}, or @samp{L} for other integer types. @cindex type modifier character (@code{printf}) @item A character that specifies the conversion to be applied. @end itemize 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. @node Table of Output Conversions @subsection Table of Output Conversions @cindex output conversions, for @code{printf} Here is a table summarizing what all the different conversions do: @table @asis @item @samp{%d}, @samp{%i} Print an integer as a signed decimal number. @xref{Integer Conversions}, for details. @samp{%d} and @samp{%i} are synonymous for output, but are different when used with @code{scanf} for input (@pxref{Table of Input Conversions}). @item @samp{%o} Print an integer as an unsigned octal number. @xref{Integer Conversions}, for details. @item @samp{%u} Print an integer as an unsigned decimal number. @xref{Integer Conversions}, for details. @item @samp{%x}, @samp{%X} Print an integer as an unsigned hexadecimal number. @samp{%x} uses lower-case letters and @samp{%X} uses upper-case. @xref{Integer Conversions}, for details. @item @samp{%f} Print a floating-point number in normal (fixed-point) notation. @xref{Floating-Point Conversions}, for details. @item @samp{%e}, @samp{%E} Print a floating-point number in exponential notation. @samp{%e} uses lower-case letters and @samp{%E} uses upper-case. @xref{Floating-Point Conversions}, for details. @item @samp{%g}, @samp{%G} Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. @samp{%g} uses lower-case letters and @samp{%G} uses upper-case. @xref{Floating-Point Conversions}, for details. @item @samp{%c} Print a single character. @xref{Other Output Conversions}. @item @samp{%s} Print a string. @xref{Other Output Conversions}. @item @samp{%p} Print the value of a pointer. @xref{Other Output Conversions}. @item @samp{%n} Get the number of characters printed so far. @xref{Other Output Conversions}. @item @samp{%%} Print a literal @samp{%} character. @xref{Other Output Conversions}. @end table @strong{Incomplete:} There also seems to be a @samp{Z} conversion for printing a @code{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. @node Integer Conversions @subsection Integer Conversions This section describes the options for the @samp{%d}, @samp{%i}, @samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion specifications. These conversions print integers in various formats. The @samp{%d} and @samp{%i} conversion specifications both print an @code{int} argument as a signed decimal number; while @samp{%o}, @samp{%u}, and @samp{%x} print the argument as an unsigned octal, decimal, or hexadecimal number (respectively). The @samp{%X} conversion specification is just like @samp{%x} except that it uses the characters @samp{ABCDEF} as digits instead of @samp{abcdef}. The following flags are meaningful: @table @asis @item @samp{-} Left-justify the result in the field (instead of the normal right-justification). @item @samp{+} For the signed @samp{%d} and @samp{%i} conversions, print a plus sign if the value is positive. @item @samp{ } For the signed @samp{%d} and @samp{%i} conversions, if the result doesn't start with a plus or minus sign, prefix it with a space character instead. Since the @samp{+} flag ensures that the result includes a sign, this flag is ignored if you supply both of them. @item @samp{#} For the @samp{%o} conversion, this forces the leading digit to be @samp{0}, as if by increasing the precision. For @samp{%x} or @samp{%X}, this prefixes a leading @samp{0x} or @samp{0X} (respectively) to the result. This doesn't do anything useful for the @samp{%d}, @samp{%i}, or @samp{%u} conversions. @item @samp{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 @samp{-} flag is also specified, or if a precision is specified. @end table 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 @code{int} (for the signed conversions @samp{%i} and @samp{%d}) or @code{unsigned int} (for the unsigned conversions @samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X}). Recall that since @code{printf} and friends are variadic, any @code{char} and @code{short} arguments are automatically converted to @code{int} by the default argument promotions. For arguments of other integer types, you can use these modifiers: @table @samp @item h Specifies that the argument is a @code{short int} or @code{unsigned short int}, as appropriate. A @code{short} argument is converted to an @code{int} or @code{unsigned int} by the default argument promotions anyway, but the @samp{h} modifier says to convert it back to a @code{short} again. @item l Specifies that the argument is a @code{long int} or @code{unsigned long int}, as appropriate. @item L Specifies that the argument is a @code{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 @code{long int}.) @end table For example, using the template string: @example |%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n" @end example @noindent to print numbers using the different options for the @samp{%d} conversion gives results like: @example | 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| @end example 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: @example "|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n" @end example @example | 0| 0| 0| 0| 0| 0x0| 0X0|0x00000000| | 1| 1| 1| 1| 01| 0x1| 0X1|0x00000001| |100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0| @end example @node Floating-Point Conversions @subsection Floating-Point Conversions This section discusses the conversion specifications for floating-point numbers: the @samp{%f}, @samp{%e}, @samp{%E}, @samp{%g}, and @samp{%G} conversions. The @samp{%f} conversion prints its argument in fixed-point notation, producing output of the form [@code{-}]@var{ddd}@code{.}@var{ddd}, where the number of digits following the decimal point is controlled by the precision you specify. The @samp{%e} conversion prints its argument in exponential notation, producing output of the form [@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}. Again, the number of digits following the decimal point is controlled by the precision. The exponent always contains at least two digits. The @samp{%E} conversion is similar but the exponent is marked with the letter @samp{E} instead of @samp{e}. The @samp{%g} and @samp{%G} conversions print the argument in the style of @samp{%e} or @samp{%E} (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the @samp{%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: @table @asis @item @samp{-} Left-justify the result in the field. Normally the result is right-justified. @item @samp{+} Always include a plus or minus sign in the result. @item @samp{ } If the result doesn't start with a plus or minus sign, prefix it with a space instead. Since the @samp{+} flag ensures that the result includes a sign, this flag is ignored if you supply both of them. @item @samp{#} Specifies that the result should always include a decimal point, even if no digits follow it. For the @samp{%g} and @samp{%G} conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed. @item @samp{0} Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the @samp{-} flag is also specified. @end table The precision specifies how many digits follow the decimal-point character for the @samp{%f}, @samp{%e}, and @samp{%E} conversions. For these conversions, the default is @code{6}. If the precision is explicitly @code{0}, this has the rather strange effect of suppressing the decimal point character entirely! For the @samp{%g} and @samp{%G} conversions, the precision specifies how many significant digits to print; if @code{0} or not specified, it is treated like a value of @code{1}. Without a type modifier, the floating-point conversions use an argument of type @code{double}. (By the default argument promotions, any @code{float} arguments are automatically converted to @code{double}.) The following type modifier is supported: @table @samp @item L An uppercase @samp{L} specifies that the argument is a @code{long double}. @end table Here are some examples showing how numbers print using the various floating-point conversions. All of the numbers were printed using this template string: @example "|%12.4f|%12.4e|%12.4g|\n" @end example Here is the output: @example | 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| @end example Notice how the @samp{%g} conversion drops trailing zeros. @node Other Output Conversions @subsection Other Output Conversions This section describes miscellaneous conversions for @code{printf}. The @samp{%c} conversion prints a single character. The @code{int} argument is first converted to an @code{unsigned char}. The @samp{-} 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: @example printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o'); @end example @noindent prints @samp{hello}. The @samp{%s} conversion prints a string. The corresponding argument must be of type @code{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 @samp{-} 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: @example printf ("%3s%-6s", "no", "where"); @end example @noindent prints @samp{ nowhere }. If you accidentally pass a null pointer as the argument for a @samp{%s} conversion, the GNU library prints it as @samp{(null)}. We think this is more useful than crashing. But it's not good practice to pass a null argument intentionally. The @samp{%p} conversion prints a pointer value. The corresponding argument must be of type @code{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 @samp{%#x} conversion were used. Null pointers print as @samp{(nil)}. (Pointers might print differently in other systems.) For example: @example printf ("%p", "testing"); @end example @noindent prints @samp{0x} followed by a hexadecimal number---the address of the string constant @code{"testing"}. It does not print the word @samp{testing}. You can supply the @samp{-} flag with the @samp{%p} conversion to specify left-justification, but no other flags, precision, or type modifiers are defined. The @samp{%n} conversion is unlike any of the other output conversions. It uses an argument which must be a pointer to an @code{int}, but instead of printing anything it stores the number of characters printed so far by this call at that location. The @samp{h} and @samp{l} type modifiers are permitted to specify that the argument is of type @code{short int *} or @code{long int *} instead of @code{int *}, but no flags, field width, or precision are permitted. For example, @example int nchar; printf ("%d %s%n\n", 3, "bears", &nchar); @end example @noindent prints: @example 3 bears @end example @noindent and sets @code{nchar} to @code{7}, because @samp{3 bears} is seven characters. The @samp{%%} conversion prints a literal @samp{%} character. This conversion doesn't use an argument, and no flags, field width, precision, or type modifiers are permitted. @node Formatted Output Functions @subsection Formatted Output Functions This section describes how to call @code{printf} and related functions. Prototypes for these functions are in the header file @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypefun int printf (const char *@var{template}, @dots{}) The @code{printf} function prints the optional arguments under the control of the template string @var{template} to the stream @code{stdout}. It returns the number of characters printed, or a negative value if there was an output error. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int fprintf (FILE *@var{stream}, const char *@var{template}, @dots{}) This function is just like @code{printf}, except that the output is written to the stream @var{stream} instead of @code{stdout}. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int sprintf (char *@var{s}, const char *@var{template}, @dots{}) This is like @code{printf}, except that the output is stored in the character array @var{s} instead of written to a stream. A null character is written to mark the end of the string. The @code{sprintf} function returns the number of characters stored in the array @var{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 @var{s} is also given as an argument to be printed under control of the @samp{%s} conversion. @xref{Copying and Concatenation}. @strong{Warning:} The @code{sprintf} function can be @strong{dangerous} because it can potentially output more characters than can fit in the allocation size of the string @var{s}. Remember that the field width given in a conversion specification is only a @emph{minimum} value. To avoid this problem, you can use @code{snprintf} or @code{asprintf}, described below. @end deftypefun @comment stdio.h @comment GNU @deftypefun int snprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, @dots{}) The @code{snprintf} function is similar to @code{sprintf}, except that the @var{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 @var{size} characters for the string @var{s}. The return value is the number of characters stored, not including the terminating null. If this value equals @var{size}, then there was not enough space in @var{s} for all the output. You should try again with a bigger output string. Here is an example of doing this: @smallexample /* @r{Print a message describing the value of a variable} @r{whose name is @var{name} and whose value is @var{value}.} */ char * make_message (char *name, char *value) @{ /* @r{Guess we need no more than 100 chars of space.} */ int size = 100; char *buffer = (char *) xmalloc (size); while (1) @{ /* @r{Try to print in the allocated space.} */ int nchars = snprintf (buffer, size, "value of %s is %s", name, value); /* @r{If that worked, return the string.} */ if (nchars < size) return buffer; /* @r{Else try again with twice as much space.} */ size *= 2; buffer = (char *) xrealloc (size, buffer); @} @} @end smallexample In practice, it is often easier just to use @code{asprintf}, below. @end deftypefun @comment stdio.h @comment GNU @deftypefun int asprintf (char **@var{ptr}, const char *@var{template}, @dots{}) This function is similar to @code{sprintf}, except that it dynamically allocates a string (as with @code{malloc}; @pxref{Unconstrained Allocation}) to hold the output, instead of putting the output in a buffer you allocate in advance. The @var{ptr} argument should be the address of a @code{char *} object, and @code{asprintf} stores a pointer to the newly allocated string at that location. Here is how to use @code{asprint} to get the same result as the @code{snprintf} example, but more easily: @smallexample /* @r{Print a message describing the value of a variable} @r{whose name is @var{name} and whose value is @var{value}.} */ char * make_message (char *name, char *value) @{ char *result; snprintf (&result, "value of %s is %s", name, value); return result; @} @end smallexample @end deftypefun @node Variable Arguments Output Functions @subsection Variable Arguments Output Functions The functions @code{vprintf} and friends are provided so that you can define your own variadic @code{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 @code{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 @code{vprintf} series, which lets you pass a @code{va_list} to describe ``all of my arguments after the first five.'' Before calling @code{vprintf} or the other functions listed in this section, you @emph{must} call @code{va_start} (@pxref{Variable Argument Facilities}) to initialize a pointer to the variable arguments. Then you can call @code{va_arg} to fetch the arguments that you want to handle yourself. This advances the pointer past those arguments. Once your @code{va_list} pointer is pointing at the argument of your choice, you are ready to call @code{vprintf}. That argument and all subsequent arguments that were passed to your function are used by @code{vprintf} along with the template that you specified separately. In some other systems, the @code{va_list} pointer may become invalid after the call to @code{vprintf}, so you must not use @code{va_arg} after you call @code{vprintf}. Instead, you should call @code{va_end} to retire the pointer from service. However, you can safely call @code{va_start} on another pointer variable and begin fetching the arguments again through that pointer. Calling @code{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 @code{va_list} pointer after passing it to @code{vprintf}, and @code{va_end} is a no-op. Prototypes for these functions are declared in @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment ANSI @deftypefun int vprintf (const char *@var{template}, va_list @var{ap}) This function is similar to @code{printf} except that, instead of taking a variable number of arguments directly, it takes an argument list pointer @var{ap}. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int vfprintf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap}) This is the equivalent of @code{fprintf} with the variable argument list specified directly as for @code{vprintf}. @end deftypefun @comment stdio.h @comment ANSI @deftypefun int vsprintf (char *@var{s}, const char *@var{template}, va_list @var{ap}) This is the equivalent of @code{sprintf} with the variable argument list specified directly as for @code{vprintf}. @end deftypefun @comment stdio.h @comment GNU @deftypefun int vsnprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, va_list @var{ap}) This is the equivalent of @code{snprintf} with the variable argument list specified directly as for @code{vprintf}. @end deftypefun @comment stdio.h @comment GNU @deftypefun int vasprintf (char **@var{ptr}, const char *@var{template}, va_list @var{ap}) The @code{vasprintf} function is the equivalent of @code{asprintf} with the variable argument list specified directly as for @code{vprintf}. @end deftypefun Here's an example showing how you might use @code{vfprintf}. This is a function that prints error messages to the stream @code{stderr}, along with a prefix indicating the name of the program. @example #include #include 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); @} @end example @noindent You could call @code{eprintf} like this: @example eprintf ("file `%s' does not exist\n", filename); @end example @node Parsing a Template String @subsection Parsing a Template String @cindex parsing a template string You can use the function @code{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 @code{printf} to avoid passing along invalid arguments from the user's program, which could cause a crash. @comment printf.h @comment GNU @deftypefun size_t parse_printf_format (const char *@var{template}, size_t @var{n}, int *@var{argtypes}) This function returns information about the number and types of arguments expected by the @code{printf} template string @var{template}. The information is stored in the array @var{argtypes}. One element of this array is used for each argument expected. This information is encoded using the various @samp{PA_} macros, listed below. The @var{n} argument specifies the number of elements in the array @var{argtypes}. This is the most elements that @code{parse_printf_format} will try to write. @code{parse_printf_format} returns the total number of arguments required by @var{template}. If this number is greater than @var{n}, then the information returned describes only the first @var{n} arguments. If you want information about more than that many arguments, allocate a bigger array and call @code{parse_printf_format} again. @end deftypefun The argument types are encoded as a combination of a basic type and modifier flag bits. @comment printf.h @comment GNU @deftypevr Macro int PA_FLAG_MASK This macro is a bitmask for the type modifier flag bits. You can write the expression @code{(argtypes[i] & PA_FLAG_MASK)} to extract just the flag bits for an argument, or @code{(argtypes[i] & ~PA_FLAG_MASK)} to extract just the basic type code. @end deftypevr Here are symbolic constants that represent the basic types; they stand for integer values. @comment printf.h @comment GNU @deftypevr Macro int PA_INT This specifies that the base type is @code{int}. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_CHAR This specifies that the base type is @code{int}, cast to @code{char}. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_STRING This specifies that the base type is @code{char *}, a null-terminated string. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_POINTER This specifies that the base type is @code{void *}, an arbitrary pointer. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_FLOAT This specifies that the base type is @code{float}. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_DOUBLE This specifies that the base type is @code{double}. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_LAST You can define additional base types for your own programs as offsets from @code{PA_LAST}. For example, if you have data types @samp{foo} and @samp{bar} with their own specialized @code{printf} conversions, you could define encodings for these types as: @example #define PA_FOO PA_LAST #define PA_BAR (PA_LAST + 1) @end example @end deftypevr Here are the flag bits that modify a basic type. They are combined with the code for the basic type using inclusive-or. @comment printf.h @comment GNU @deftypevr 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, @samp{PA_INT|PA_FLAG_PTR} represents the type @samp{int *}. @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_FLAG_SHORT If this bit is set, it indicates that the base type is modified with @code{short}. (This corresponds to the @samp{h} type modifier.) @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_FLAG_LONG If this bit is set, it indicates that the base type is modified with @code{long}. (This corresponds to the @samp{l} type modifier.) @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_FLAG_LONGLONG If this bit is set, it indicates that the base type is modified with @code{long long}. (This corresponds to the @samp{L} type modifier.) @end deftypevr @comment printf.h @comment GNU @deftypevr Macro int PA_FLAG_LONGDOUBLE This is a synonym for @code{PA_FLAG_LONGLONG}, used by convention with a base type of @code{PA_DOUBLE} to indicate a type of @code{long double}. @end deftypevr @strong{Incomplete:} Should have an example here from a fictional interpreter, showing how one might validate a list of args and then call @code{vprintf}. @node Customizing Printf @section Customizing Printf @cindex customizing @code{printf} @cindex defining new @code{printf} conversions @cindex extending @code{printf} The GNU C library lets you define your own custom conversion specifiers for @code{printf} template strings, to teach @code{printf} clever ways to print the important data structures of your program. The way you do this is by registering the conversion with @code{register_printf_function}; see @ref{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 @ref{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. @xref{Parsing a Template String}, for information about this. The facilities of this section are declared in the header file @file{printf.h}. @menu * Registering New Conversions:: * Conversion Specifier Options:: * Defining the Output Handler:: * Printf Extension Example:: @end menu @strong{Portability Note:} The ability to extend the syntax of @code{printf} template strings is a GNU extension. ANSI standard C has nothing similar. @node Registering New Conversions @subsection Registering New Conversions The function to register a new output conversion is @code{register_printf_function}, declared in @file{printf.h}. @pindex printf.h @comment printf.h @comment GNU @deftypefun int register_printf_function (int @var{spec}, printf_function @var{handler_function}, printf_arginfo_function @var{arginfo_function}) This function defines the conversion specifier character @var{spec}. Thus, if @var{spec} is @code{'q'}, it defines the conversion @samp{%q}. The @var{handler_function} is the function called by @code{printf} and friends when this conversion appears in a template string. @xref{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 @var{spec} is removed. The @var{arginfo_function} is the function called by @code{parse_printf_format} when this conversion appears in a template string. @xref{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 @code{parse_printf_format}, you do not need to define an arginfo function. The return value is @code{0} on success, and @code{-1} on failure (which occurs if @var{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. @end deftypefun @node Conversion Specifier Options @subsection Conversion Specifier Options If you define a meaning for @samp{%q}, what if the template contains @samp{%+Sq} or @samp{%-#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 @var{handler_function} and @var{arginfo_function} arguments to @code{register_printf_function} accept an argument of type @code{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 @file{printf.h}. @pindex printf.h @comment printf.h @comment GNU @deftp {struct Type} printf_info This structure is used to pass information about the options appearing in an instance of a conversion specifier in a @code{printf} template string to the handler and arginfo functions for that specifier. It contains the following members: @table @code @item int prec This is the precision specified. The value is @code{-1} if no precision was specified. If the precision was given as @samp{*}, the @code{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 @code{INT_MIN}, since the actual value is not known. @item int width This is the minimum field width specified. The value is @code{0} if no width was specified. If the field width was given as @samp{*}, the @code{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 @code{INT_MIN}, since the actual value is not known. @item 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. @item unsigned int is_long_double This is a boolean that is true if the @samp{L} type modifier was specified. @item unsigned int is_short This is a boolean that is true if the @samp{h} type modifier was specified. @item unsigned int is_long This is a boolean that is true if the @samp{l} type modifier was specified. @item unsigned int alt This is a boolean that is true if the @samp{#} flag was specified. @item unsigned int space This is a boolean that is true if the @samp{ } flag was specified. @item unsigned int left This is a boolean that is true if the @samp{-} flag was specified. @item unsigned int showsign This is a boolean that is true if the @samp{+} flag was specified. @item char pad This is the character to use for padding the output to the minimum field width. The value is @code{'0'} if the @samp{0} flag was specified, and @code{' '} otherwise. @end table @end deftp @node Defining the Output Handler @subsection Defining the Output Handler Now let's look at how to define the handler and arginfo functions which are passed as arguments to @code{register_printf_function}. You should define your handler functions with a prototype like: @example int @var{function} (FILE *stream, const struct printf_info *info, va_list *ap_pointer) @end example The @code{stream} argument passed to the handler function is the stream to which it should write output. The @code{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. @xref{Conversion Specifier Options}, for a description of this data structure. The @code{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 @emph{pointer} to a @code{va_list}, rather than the @code{va_list} itself. Thus, you should fetch arguments by means of @code{va_arg (@var{type}, *ap_pointer)}. (Passing a pointer here allows the function that calls your handler function to update its own @code{va_list} variable to account for the arguments that your handler processes. @xref{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 @code{-1} to indicate an error. @comment printf.h @comment GNU @deftp {Data Type} printf_function This is the data type that a handler function should have. @end deftp If you are going to use @code{parse_printf_format} in your application, you should also define a function to pass as the @var{arginfo_function} argument for each new conversion you install with @code{register_printf_function}. You should define these functions with a prototype like: @example int @var{function} (const struct printf_info *info, size_t n, int *argtypes) @end example The return value from the function should be the number of arguments the conversion expects, up to a maximum of @var{n}. The function should also fill in the @var{argtypes} array with information about the types of each of these arguments. This information is encoded using the various @samp{PA_} macros. @comment printf.h @comment GNU @deftp {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. @end deftp @node Printf Extension Example @subsection Printf Extension Example Here is an example showing how to define a @code{printf} handler function. This program defines a data structure called a @code{Widget} and defines the @samp{%W} conversion to print information about @code{Widget *} arguments, including the pointer value and the name stored in the data structure. The @samp{%W} conversion supports the minimum field width and left-justification options, but ignores everything else. @example #include #include #include struct widget @{ char *name; @dots{} @}; int print_widget (FILE *stream, const struct printf_info *info, va_list *app) @{ struct widget *w; char *buffer; int padding_amount, i; /* @r{Fetch the widget to be printed.} */ w = va_arg (*app, struct widget *); /* @r{Format the output into a string.} */ padding_amount = (info->width - asprintf (&buffer, "", w, w->name)); /* @r{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); /* @r{Clean up and return.} */ free (buffer); return 1; @} void main (void) @{ /* @r{Make a widget to print.} */ struct widget mywidget; mywidget.name = "mywidget"; /* @r{Register the print function for widgets.} */ register_printf_function ('W', print_widget, NULL); /* @r{Now print the widget.} */ printf ("|%W|\n", &mywidget); printf ("|%35W|\n", &mywidget); printf ("|%-35W|\n", &mywidget); @} @end example The output produced by this program looks like: @example || | | | | @end example @node Formatted Input @section Formatted Input @cindex formatted input from a stream @cindex reading from a stream, formatted @cindex format string, for @code{scanf} @cindex template, for @code{scanf} The functions described in this section (@code{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 @dfn{format string} or @dfn{template string}. @menu * Formatted Input Basics:: Some basics to get you started. * Input Conversion Syntax:: Syntax of conversion specifications. * Table of Input Conversions:: Summary of input conversions and what they do. * Numeric Input Conversions:: Details of conversions for reading numbers. * String Input Conversions:: Details of conversions for reading strings. * Other Input Conversions:: Details of miscellaneous other conversions. * Formatted Input Functions:: Descriptions of the actual functions. * Variable Arguments Input Functions:: @code{vscanf} and friends. @end menu @node Formatted Input Basics @subsection Formatted Input Basics Calls to @code{scanf} are superficially similar to calls to @code{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 @code{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 @code{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. @cindex conversion specifications (@code{scanf}) Another area of difference between @code{scanf} and @code{printf} is that you must remember to supply pointers rather than immediate values as the optional arguments to @code{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 @code{scanf}, you might want to double-check this. When a @dfn{matching failure} occurs, @code{scanf} returns immediately, leaving the first non-matching character as the next character to be read from the stream. The normal return value from @code{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. @cindex matching failure, in @code{scanf} The @code{scanf} function is typically used to do things like reading in the contents of tables. For example, here is a function that uses @code{scanf} to initialize an array of @code{double}s: @example void readarray (double *array, int n) @{ int i; for (i=0; i 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); @} @end example This program produces the following output: @example Got f Got o Got o Got b Got a Got r @end example @comment stdio.h @comment GNU @deftypefun {FILE *} open_memstream (char **@var{ptr}, size_t @var{sizeloc}) This function opens a stream for writing to a buffer. The buffer is allocated dynamically (as with @code{malloc}; @pxref{Unconstrained Allocation}) and grown as necessary. When the stream is closed with @code{fclose} or flushed with @code{fflush}, the locations @var{ptr} and @var{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 @emph{not} included in the size value stored at @var{sizeloc}. @end deftypefun Here is an example of using @code{open_memstream}: @example #include 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); @} @end example This program produces the following output: @example buf = `hello', size = 5 buf = `hello, world', size = 12 @end example @node Custom Streams @subsection Programming Your Own Custom Streams @cindex custom streams @cindex programming your own 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 @dfn{custom streams}. @menu * Streams and Cookies:: * Hook Functions:: @end menu @node Streams and Cookies @subsubsection Custom Streams and Cookies @cindex cookie, for custom stream Inside every custom stream is a special object called the @dfn{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 @code{void *}. To implement custom stream, you must specify @emph{how} to fetch or store the data in the specified place. You do this by defining @dfn{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 @code{__io_functions}. These facilities are declared in @file{stdio.h}. @pindex stdio.h @comment stdio.h @comment GNU @deftp {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: @table @code @item __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 @code{EOF}. @item __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. @item __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 @code{fseek} on this stream return an @code{ESPIPE} error. @item __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. @end table @end deftp @comment stdio.h @comment GNU @deftypefun {FILE *} fopencookie (void *@var{cookie}, const char *@var{opentype}, __io_functions @var{io_functions}) This function actually creates the stream for communicating with the @var{cookie} using the functions in the @var{io_functions} argument. The @var{opentype} argument is interpreted as for @code{fopen}; see @ref{Opening and Closing Streams}. (But note that the ``truncate on open'' option is ignored.) @strong{Incomplete:} What is the default buffering mode for the newly created stream? The @code{fopencookie} function returns the newly created stream, or a null pointer in case of an error. @end deftypefun @node Hook Functions @subsubsection Custom Stream Hook Functions @cindex hook functions (of custom streams) 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: @example int @var{function} (void *@var{cookie}, void *@var{buffer}, size_t @var{size}) @end example This is very similar to the @code{read} function; see @ref{I/O Primitives}. Your function should transfer up to @var{size} bytes into the @var{buffer}, and return the number of bytes read. You can return a value of @code{-1} to indicate an error. You should define the function to write data to the cookie as: @example int @var{function} (void *@var{cookie}, const void *@var{buffer}, size_t @var{size}) @end example This is very similar to the @code{write} function; see @ref{I/O Primitives}. Your function should transfer up to @var{size} bytes from the buffer, and return the number of bytes written. You can return a value of @code{-1} to indicate an error. You should define the function to perform seek operations on the cookie as: @example int @var{function} (void *@var{cookie}, fpos_t *@var{position}, int @var{whence}) @end example For this function, the @code{position} and @code{whence} arguments are interpreted as for @code{fgetpos}; see @ref{Text and Binary Streams}. Remember that in the GNU system, @code{fpos_t} is equivalent to @code{off_t} or @code{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 @var{position}. Your function should return a value of @code{0} on success and @code{-1} to indicate an error. You should define the function to do cleanup operations on the cookie appropriate for closing the stream as: @example int @var{function} (void *@var{cookie}) @end example Your function should return @code{-1} to indicate an error, and @code{0} otherwise. @comment stdio.h @comment GNU @deftp {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. @end deftp @comment stdio.h @comment GNU @deftp {Data Type} __io_write The data type of the write function for a custom stream. @end deftp @comment stdio.h @comment GNU @deftp {Data Type} __io_seek The data type of the seek function for a custom stream. @end deftp @comment stdio.h @comment GNU @deftp {Data Type} __io_close The data type of the close function for a custom stream. @end deftp @ignore @strong{Incomplete:} Roland says: @quotation There is another set of functions one can give a stream, the input-room and output-room functions. These functions must understand stdio internals. To describe how to use these functions, you also need to document lots of how stdio works internally (which isn't relevant for other uses of stdio). Perhaps I can write an interface spec from which you can write good documentation. But it's pretty complex and deals with lots of nitty-gritty details. I think it might be better to let this wait until the rest of the manual is more done and polished. @end quotation @end ignore @strong{Incomplete:} This section could use an example.