@Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.
Œ

ˆ‰SEC75Št�”›Input/Output on Streams

@�”˜This chapter describes the functions for creating streams and performing input and output operations on them. As discussed in section ‰ŠP�”›Input/Output Overview@�”˜, a stream is a fairly abstract, high-level concept representing a communications channel to a file, device, or process.
ˆ‰SEC76Št�”›Streams

@�”˜For historical reasons, the type of the C data structure that represents a stream is called HFILE@ rather than "stream". Since most of the library functions deal with objects of type HFILE *@, sometimes the term Bfile 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. ‰IDX431Š
‰IDX432Š@�”˜The HFILE@ type is declared in the header file H`stdio.h'@.

AData Type:@ DFILE
Â‰IDX433Š@�”˜This is the data type used to represent stream objects. A HFILE@ 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 Hferror@ and Hfeof@ functions; see section ‰ŠP�”›End-Of-File and Errors@�”˜.À

HFILE@ objects are allocated and managed internally by the input/output library functions. Don't try to create your own objects of type HFILE@; let the library do it. Your programs should deal only with pointers to these objects (that is, HFILE *@ values) rather than the objects themselves.
ˆ‰SEC77Št�”›Standard Streams

‰IDX434Š‰IDX435Š
@�”˜When the Hmain@ function of your program is invoked, it already has three predefined streams open and available for use. These represent the "standard" input and output channels that have been established for the process.
These streams are declared in the header file H`stdio.h'@. ‰IDX436Š

A�”˜Variable:@ FILE * Dstdin
Â‰IDX437Š@�”˜The Bstandard input@ stream, which is the normal source of input for the program.À
‰IDX438Š

A�”˜Variable:@ FILE * Dstdout
Â‰IDX439Š@�”˜The Bstandard output@ stream, which is used for normal output from the program.À
‰IDX440Š

A�”˜Variable:@ FILE * Dstderr
Â‰IDX441Š@�”˜The Bstandard error@ stream, which is used for error messages and diagnostics issued by the program.À
‰IDX442Š
@�”˜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 section ‰ŠP�”›File System Interface@�”˜.) Most other operating systems provide similar mechanisms, but the details of how to use them can vary.
In the GNU C library, Hstdin@, Hstdout@, and Hstderr@ are normal variables which you can set just like any others. For example, to redirect the standard output to a file, you could do: fclose (stdout);
stdout = fopen ("standard-output-file", "w");
Note however, that in other systems Hstdin@, Hstdout@, and Hstderr@ are macros that you cannot assign to in the normal way. But you can use Hfreopen@ to get the effect of closing one and reopening it. See section ‰ŠP�”›Opening Streams@�”˜.
ˆ‰SEC78Št�”›Opening Streams

‰IDX443Š@�”˜Opening a file with the Hfopen@ function creates a new stream and establishes a connection between the stream and a file. This may involve creating a new file.
‰IDX444Š@�”˜Everything described in this section is declared in the header file H`stdio.h'@.

AFunction:@ FILE * Dfopen@ B(const char *Bfilename@, const char *Bopentype@)
Â‰IDX445Š@�”˜The Hfopen@ function opens a stream for I/O to the file Bfilename@, and returns a pointer to the stream.
The Bopentype@ 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:
H`r'
Ä@Open an existing file for reading only.
ÂH`w'
Ä@Open the file for writing only. If the file already exists, it is truncated to zero length. Otherwise a new file is created.
ÂH`a'
Ä@Open a file for append access; that is, writing at the end of file only. If the file already exists, its initial contents are unchanged and output to the stream is appended to the end of the file. Otherwise, a new, empty file is created.
ÂH`r+'
Ä@Open an existing file for both reading and writing. The initial contents of the file are unchanged and the initial file position is at the beginning of the file.
ÂH`w+'
Ä@Open a file for both reading and writing. If the file already exists, it is truncated to zero length. Otherwise, a new file is created.
ÂH`a+'
Ä@Open or create file for both reading and appending. If the file exists, its initial contents are unchanged. Otherwise, a new file is created. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.Â

As you can see, H`+'@ requests a stream that can do both input and output. The ISO standard says that when using such a stream, you must call Hfflush@ (see section ‰ŠP�”›Stream Buffering@�”˜) or a file positioning function such as Hfseek@ (see section ‰ŠP�”›File Positioning@�”˜) when switching from reading to writing or vice versa. Otherwise, internal buffers might not be emptied properly. The GNU C library does not have this limitation; you can do arbitrary reading and writing operations on a stream in whatever order.
Additional characters may appear after these to specify flags for the call. Always put the mode (H`r'@, H`w+'@, etc.) first; that is the only part you are guaranteed will be understood by all systems.
The GNU C library defines one additional character for use in Bopentype@: the character H`x'@ insists on creating a new file--if a file Bfilename@ already exists, Hfopen@ fails rather than opening it. If you use H`x'@ you can are guaranteed that you will not clobber an existing file. This is equivalent to the HO_EXCL@ option to the Hopen@ function (see section ‰ŠP�”›Opening and Closing Files@�”˜).
The character H`b'@ in Bopentype@ has a standard meaning; it requests a binary stream rather than a text stream. But this makes no difference in POSIX systems (including the GNU system). If both H`+'@ and H`b'@ are specified, they can appear in either order. See section ‰ŠP�”›Text and Binary Streams@�”˜.
Any other characters in Bopentype@ are simply ignored. They may be meaningful in other systems.
If the open fails, Hfopen@ returns a null pointer.À

You can have multiple streams (or file descriptors) pointing to the same file open at the same time. If you do only input, this works straightforwardly, but you must be careful if any output streams are included. See section ‰ŠP�”›Dangers of Mixing Streams and Descriptors@�”˜. This is equally true whether the streams are in one program (not usual) or in several programs (which can easily happen). It may be advantageous to use the file locking facilities to avoid simultaneous access. See section ‰ŠP�”›File Locks@�”˜.

AMacro:@ int DFOPEN_MAX
Â‰IDX446Š@�”˜The value of this macro is an integer constant expression that represents the minimum number of streams that the implementation guarantees can be open simultaneously. You might be able to open more than this many streams, but that is not guaranteed. The value of this constant is at least eight, which includes the three standard streams Hstdin@, Hstdout@, and Hstderr@. In POSIX.1 systems this value is determined by the HOPEN_MAX@ parameter; see section ‰ŠP�”›General Capacity Limits@�”˜. In BSD and GNU, it is controlled by the HRLIMIT_NOFILE@ resource limit; see section ‰ŠP�”›Limiting Resource Usage@�”˜.À

AFunction:@ FILE * Dfreopen@ B(const char *Bfilename@, const char *Bopentype@, FILE *Bstream@)
Â‰IDX447Š@�”˜This function is like a combination of Hfclose@ and Hfopen@. It first closes the stream referred to by Bstream@, ignoring any errors that are detected in the process. (Because errors are ignored, you should not use Hfreopen@ on an output stream if you have actually done any output using the stream.) Then the file named by Bfilename@ is opened with mode Bopentype@ as for Hfopen@, and associated with the same stream object Bstream@.
If the operation fails, a null pointer is returned; otherwise, Hfreopen@ returns Bstream@.
Hfreopen@ has traditionally been used to connect a standard stream such as Hstdin@ with a file of your own choice. This is useful in programs in which use of a standard stream for certain purposes is hard-coded. In the GNU C library, you can simply close the standard streams and open new ones with Hfopen@. But other systems lack this ability, so using Hfreopen@ is more portable.À

ˆ‰SEC79Št�”›Closing Streams

‰IDX448Š@�”˜When a stream is closed with Hfclose@, the connection between the stream and the file is cancelled. After you have closed a stream, you cannot perform any additional operations on it.

AFunction:@ int Dfclose@ B(FILE *Bstream@)
Â‰IDX449Š@�”˜This function causes Bstream@ 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 Hfclose@ function returns a value of H0@ if the file was closed successfully, and HEOF@ if an error was detected.
It is important to check for errors when you call Hfclose@ to close an output stream, because real, everyday errors can be detected at this time. For example, when Hfclose@ writes the remaining buffered output, it might get an error because the disk is full. Even if you know the buffer is empty, errors can still occur when closing a file if you are using NFS.
The function Hfclose@ is declared in H`stdio.h'@.À

To close all streams currently available the GNU C Library provides another function.

AFunction:@ int Dfcloseall@ B(void)
Â‰IDX450Š@�”˜This function causes all open streams of the process to be closed and the connection to corresponding files to be broken. All buffered data is written and any buffered inputis discarded. The Hfcloseall@ function returns a value of H0@ if all the files were closed successfully, and HEOF@ if an error was detected.
This function should be used in only in special situation, e.g., when an error occurred and the program must be aborted. Normally each single stream should be closed separately so that problems with one stream can be identifier. It is also problematic since the standard streams (see section ‰ŠP�”›Standard Streams@�”˜) will also be closed.
The function Hfcloseall@ is declared in H`stdio.h'@.À

If the Hmain@ function to your program returns, or if you call the Hexit@ function (see section ‰ŠP�”›Normal Termination@�”˜), all open streams are automatically closed properly. If your program terminates in any other manner, such as by calling the Habort@ function (see section ‰ŠP�”›Aborting a Program@�”˜) or from a fatal signal (see section ‰ŠP�”›Signal Handling@�”˜), open streams might not be closed properly. Buffered output might not be flushed and files may be incomplete. For more information on buffering of streams, see section ‰ŠP�”›Stream Buffering@�”˜.
ˆ‰SEC80Št�”›Simple Output by Characters or Lines

‰IDX451Š@�”˜This section describes functions for performing character- and line-oriented output.
These functions are declared in the header file H`stdio.h'@. ‰IDX452Š

A�”˜Function:@ int Dfputc@ B(int Bc@, FILE *Bstream@)
Â‰IDX453Š@�”˜The Hfputc@ function converts the character Bc@ to type Hunsigned char@, and writes it to the stream Bstream@. HEOF@ is returned if a write error occurs; otherwise the character Bc@ is returned.À

AFunction:@ int Dputc@ B(int Bc@, FILE *Bstream@)
Â‰IDX454Š@�”˜This is just like Hfputc@, except that most systems implement it as a macro, making it faster. One consequence is that it may evaluate the Bstream@ argument more than once, which is an exception to the general rule for macros. Hputc@ is usually the best function to use for writing a single character.À

AFunction:@ int Dputchar@ B(int Bc@)
Â‰IDX455Š@�”˜The Hputchar@ function is equivalent to Hputc@ with Hstdout@ as the value of the Bstream@ argument.À

AFunction:@ int Dfputs@ B(const char *Bs@, FILE *Bstream@)
Â‰IDX456Š@�”˜The function Hfputs@ writes the string Bs@ to the stream Bstream@. The terminating null character is not written. This function does Bnot@ add a newline character, either. It outputs only the characters in the string.
This function returns HEOF@ 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 H`Are you hungry?'@ followed by a newline.À

AFunction:@ int Dputs@ B(const char *Bs@)
Â‰IDX457Š@�”˜The Hputs@ function writes the string Bs@ to the stream Hstdout@ followed by a newline. The terminating null character of the string is not written. (Note that Hfputs@ does Bnot@ write a newline as this function does.)
Hputs@ is the most convenient function for printing simple messages. For example: puts ("This is a message."); À

AFunction:@ int Dputw@ B(int Bw@, FILE *Bstream@)
Â‰IDX458Š@�”˜This function writes the word Bw@ (that is, an Hint@) to Bstream@. It is provided for compatibility with SVID, but we recommend you use Hfwrite@ instead (see section ‰ŠP�”›Block Input/Output@�”˜).À

ˆ‰SEC81Št�”›Character Input

‰IDX459Š@�”˜This section describes functions for performing character-oriented input. These functions are declared in the header file H`stdio.h'@. ‰IDX460Š
@�”˜These functions return an Hint@ value that is either a character of input, or the special value HEOF@ (usually -1). It is important to store the result of these functions in a variable of type Hint@ instead of Hchar@, even when you plan to use it only as a character. Storing HEOF@ in a Hchar@ variable truncates its value to the size of a character, so that it is no longer distinguishable from the valid character H`(char) -1'@. So always use an Hint@ for the result of Hgetc@ and friends, and check for HEOF@ after the call; once you've verified that the result is not HEOF@, you can be sure that it will fit in a H`char'@ variable without loss of information.

AFunction:@ int Dfgetc@ B(FILE *Bstream@)
Â‰IDX461Š@�”˜This function reads the next character as an Hunsigned char@ from the stream Bstream@ and returns its value, converted to an Hint@. If an end-of-file condition or read error occurs, HEOF@ is returned instead.À

AFunction:@ int Dgetc@ B(FILE *Bstream@)
Â‰IDX462Š@�”˜This is just like Hfgetc@, except that it is permissible (and typical) for it to be implemented as a macro that evaluates the Bstream@ argument more than once. Hgetc@ is often highly optimized, so it is usually the best function to use to read a single character.À

AFunction:@ int Dgetchar@ B(void)
Â‰IDX463Š@�”˜The Hgetchar@ function is equivalent to Hgetc@ with Hstdin@ as the value of the Bstream@ argument.À

Here is an example of a function that does input using Hfgetc@. It would work just as well using Hgetc@ instead, or using Hgetchar ()@ instead of Hfgetc (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 != EOF)
c = fgetc (stdin);
/* Obey the answer if it was valid. */
if (answer == 'y')
return 1;
if (answer == 'n')
return 0;
/* Answer was invalid: ask for valid answer. */
fputs ("Please answer y or n:", stdout);
}
}

AFunction:@ int Dgetw@ B(FILE *Bstream@)
Â‰IDX464Š@�”˜This function reads a word (that is, an Hint@) from Bstream@. It's provided for compatibility with SVID. We recommend you use Hfread@ instead (see section ‰ŠP�”›Block Input/Output@�”˜). Unlike Hgetc@, any Hint@ value could be a valid result. Hgetw@ returns HEOF@ when it encounters end-of-file or an error, but there is no way to distinguish this from an input word with value -1.À

ˆ‰SEC82Št�”›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 Hgets@) long lines can confuse them. So the GNU library provides the nonstandard Hgetline@ function that makes it easy to read lines reliably.
Another GNU extension, Hgetdelim@, generalizes Hgetline@. It reads a delimited record, defined as everything through the next occurrence of a specified delimiter character.
All these functions are declared in H`stdio.h'@.

AFunction:@ ssize_t Dgetline@ B(char **Blineptr@, size_t *Bn@, FILE *Bstream@)
Â‰IDX465Š@�”˜This function reads an entire line from Bstream@, storing the text (including the newline and a terminating null character) in a buffer and storing the buffer address in H*Jlineptr@.
Before calling Hgetline@, you should place in H*Jlineptr@ the address of a buffer H*Jn@ bytes long, allocated with Hmalloc@. If this buffer is long enough to hold the line, Hgetline@ stores the line in this buffer. Otherwise, Hgetline@ makes the buffer bigger using Hrealloc@, storing the new buffer address back in H*Jlineptr@ and the increased size back in H*Jn@. See section ‰ŠP�”›Unconstrained Allocation@�”˜.
If you set H*Jlineptr@ to a null pointer, and H*Jn@ to zero, before the call, then Hgetline@ allocates the initial buffer for you by calling Hmalloc@.
In either case, when Hgetline@ returns, H*Jlineptr@ is a Hchar *@ which points to the text of the line.
When Hgetline@ 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, Hgetline@ returns H-1@.À

AFunction:@ ssize_t Dgetdelim@ B(char **Blineptr@, size_t *Bn@, int Bdelimiter@, FILE *Bstream@)
Â‰IDX466Š@�”˜This function is like Hgetline@ except that the character which tells it to stop reading is not necessarily newline. The argument Bdelimiter@ specifies the delimiter character; Hgetdelim@ keeps reading until it sees that character (or end of file).
The text is stored in Blineptr@, including the delimiter character and a terminating null. Like Hgetline@, Hgetdelim@ makes Blineptr@ bigger if it isn't big enough.
Hgetline@ is in fact implemented in terms of Hgetdelim@, just like this: ssize_t
getline (char **lineptr, size_t *n, FILE *stream)
{
return getdelim (lineptr, n, '\n', stream);
} À

AFunction:@ char * Dfgets@ B(char *Bs@, int Bcount@, FILE *Bstream@)
Â‰IDX467Š@�”˜The Hfgets@ function reads characters from the stream Bstream@ up to and including a newline character and stores them in the string Bs@, adding a null character to mark the end of the string. You must supply Bcount@ characters worth of space in Bs@, but the number of characters read is at most Bcount@ - 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 Hfgets@, then the contents of the array Bs@ 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 Bs@.
DWarning:@ If the input data has a null character, you can't tell. So don't use Hfgets@ 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 Hgetline@ instead of Hfgets@.À

ADeprecated function:@ char * Dgets@ B(char *Bs@)
Â‰IDX468Š@�”˜The function Hgets@ reads characters from the stream Hstdin@ up to the next newline character, and stores them in the string Bs@. The newline character is discarded (note that this differs from the behavior of Hfgets@, which copies the newline character into the string). If Hgets@ encounters a read error or end-of-file, it returns a null pointer; otherwise it returns Bs@.
DWarning:@ The Hgets@ function is Dvery dangerous@ because it provides no protection against overflowing the string Bs@. The GNU library includes it for compatibility only. You should Dalways@ use Hfgets@ or Hgetline@ instead. To remind you of this, the linker (if using GNU Hld@) will issue a warning whenever you use Hgets@.À

ˆ‰SEC83Št�”›Unreading

‰IDX469Š‰IDX470Š‰IDX471Š
@�”˜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 Bunreading@ it (also called Bpushing it back@ on the stream). Unreading a character makes it available to be input again from the stream, by the next call to Hfgetc@ or other input function on that stream.
ˆ‰SEC84ŠT�”›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 H`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 H`b'@.
If instead of reading H`b'@ you unread the letter H`o'@, you get a situation like this: f o o b a r
|
o--
^
so that the next input characters will be H`o'@ and H`b'@.
If you unread H`9'@ instead of H`o'@, you get this situation: f o o b a r
|
9--
^
so that the next input characters will be H`9'@ and H`b'@.
ˆ‰SEC85ŠT�”›Using \ungetcT To Do Unreading

@�”˜The function to unread a character is called Hungetc@, because it reverses the action of Hgetc@.

AFunction:@ int Dungetc@ B(int Bc@, FILE *Bstream@)
Â‰IDX472Š@�”˜The Hungetc@ function pushes back the character Bc@ onto the input stream Bstream@. So the next input from Bstream@ will read Bc@ before anything else.
If Bc@ is HEOF@, Hungetc@ does nothing and just returns HEOF@. This lets you call Hungetc@ with the return value of Hgetc@ without needing to check for an error from Hgetc@.
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 Hungetc@! But that is a strange way to write a program; usually Hungetc@ 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 Hungetc@ 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 Hfseek@ or Hrewind@; see section ‰ŠP�”›File Positioning@�”˜) is called, any pending pushed-back characters are discarded.
Unreading a character on a stream that is at end of file clears the end-of-file indicator for the stream, because it makes the character of input available. After you read that character, trying to read again will encounter end of file.À

Here is an example showing the use of Hgetc@ and Hungetc@ to skip over whitespace characters. When this function reaches a non-whitespace character, it unreads that character to be seen again on the next read operation on the stream. #include <stdio.h>
#include <ctype.h>

void
skip_whitespace (FILE *stream)
{
int c;
do
/* No need to check for HEOF@ because it is not
Hisspace@, and Hungetc@ ignores HEOF@. */
c = getc (stream);
while (isspace (c));
ungetc (c, stream);
}
ˆ‰SEC86Št�”›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. ‰IDX473Š‰IDX474Š‰IDX475Š‰IDX476Š
@�”˜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 H`stdio.h'@. ‰IDX477Š

A�”˜Function:@ size_t Dfread@ B(void *Bdata@, size_t Bsize@, size_t Bcount@, FILE *Bstream@)
Â‰IDX478Š@�”˜This function reads up to Bcount@ objects of size Bsize@ into the array Bdata@, from the stream Bstream@. It returns the number of objects actually read, which might be less than Bcount@ 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 Bsize@ or Bcount@ is zero.
If Hfread@ 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.À

AFunction:@ size_t Dfwrite@ B(const void *Bdata@, size_t Bsize@, size_t Bcount@, FILE *Bstream@)
Â‰IDX479Š@�”˜This function writes up to Bcount@ objects of size Bsize@ from the array Bdata@, to the stream Bstream@. The return value is normally Bcount@, if the call succeeds. Any other value indicates some sort of error, such as running out of space.À

ˆ‰SEC87Št�”›Formatted Output

‰IDX480Š‰IDX481Š‰IDX482Š‰IDX483Š@�”˜The functions described in this section (Hprintf@ and related functions) provide a convenient way to perform formatted output. You call Hprintf@ with a Bformat string@ or Btemplate 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 Hprintf@ 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.
ˆ‰SEC88ŠT�”›Formatted Output Basics

@�”˜The Hprintf@ 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 Bconversion specifications@ introduced by a H`%'@ character in the template cause subsequent arguments to be formatted and written to the output stream. For example, ‰IDX484Š@�”˜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 H`%d'@ conversion to specify that an Hint@ argument should be printed in decimal notation, the H`%s'@ conversion to specify printing of a string argument, and the H`%%'@ conversion to print a literal H`%'@ character.
There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (H`%o'@, H`%u'@, or H`%x'@, respectively); or as a character value (H`%c'@).
Floating-point numbers can be printed in normal, fixed-point notation using the H`%f'@ conversion or in exponential notation using the H`%e'@ conversion. The H`%g'@ conversion uses either H`%e'@ or H`%f'@ format, depending on what is more appropriate for the magnitude of the particular number.
You can control formatting more precisely by writing Bmodifiers@ between the H`%'@ and the character that indicates which conversion to apply. These slightly alter the ordinary behavior of the conversion. For example, most conversion specifications permit you to specify a minimum field width and a flag indicating whether you want the result left- or right-justified within the field.
The specific flags and modifiers that are permitted and their interpretation vary depending on the particular conversion. They're all described in more detail in the following sections. Don't worry if this all seems excessively complicated at first; you can almost always get reasonable free-format output without using any of the modifiers at all. The modifiers are mostly used to make the output look "prettier" in tables.
ˆ‰SEC89ŠT�”›Output Conversion Syntax

@�”˜This section provides details about the precise syntax of conversion specifications that can appear in a Hprintf@ 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 section ‰ŠP�”›Extended Characters@�”˜) are permitted in a template string.
The conversion specifications in a Hprintf@ template string have the general form: % Bflags@ Bwidth@ [ . Bprecision@ ] Btype@ Bconversion@
For example, in the conversion specifier H`%-10.8ld'@, the H`-'@ is a flag, H`10'@ specifies the field width, the precision is H`8'@, the letter H`l'@ is a type modifier, and H`d'@ specifies the conversion style. (This particular type specifier says to print a Hlong 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 H`%'@ character followed in sequence by: þÂ
• Zero or more Bflag characters@ that modify the normal behavior of the conversion specification. ‰IDX485Š
• @�”˜An optional decimal integer specifying the Bminimum field width@. If the normal conversion produces fewer characters than this, the field is padded with spaces to the specified width. This is a Bminimum@ value; if the normal conversion produces more characters than this, the field is Bnot@ truncated. Normally, the output is right-justified within the field. ‰IDX486Š@�”˜You can also specify a field width of H`*'@. 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 Hint@. If the value is negative, this means to set the H`-'@ flag (see below) and to use the absolute value as the field width.
• An optional Bprecision@ to specify the number of digits to be written for the numeric conversions. If the precision is specified, it consists of a period (H`.'@) followed optionally by a decimal integer (which defaults to zero if omitted). ‰IDX487Š@�”˜You can also specify a precision of H`*'@. 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 Hint@, and is ignored if it is negative. If you specify H`*'@ 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 Btype 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 Hint@, but you can specify H`h'@, H`l'@, or H`L'@ for other integer types.) ‰IDX488Š
• @�”˜A character that specifies the conversion to be applied.Àð
The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they use.
With the H`-Wformat'@ option, the GNU C compiler checks calls to Hprintf@ and related functions. It examines the format string and verifies that the correct number and types of arguments are supplied. There is also a GNU C syntax to tell the compiler that a function you write uses a Hprintf@-style format string. See section `Declaring Attributes of Functions' in BUsing GNU CC@, for more information.
ˆ‰SEC90ŠT�”›Table of Output Conversions

‰IDX489Š
@�”˜Here is a table summarizing what all the different conversions do:
H`%d'@, H`%i'
Â@Print an integer as a signed decimal number. See section ‰ŠP�”›Integer Conversions@�”˜, for details. H`%d'@ and H`%i'@ are synonymous for output, but are different when used with Hscanf@ for input (see section ‰ŠP�”›Table of Input Conversions@�”˜).
ÀH`%o'
Â@Print an integer as an unsigned octal number. See section ‰ŠP�”›Integer Conversions@�”˜, for details.
ÀH`%u'
Â@Print an integer as an unsigned decimal number. See section ‰ŠP�”›Integer Conversions@�”˜, for details.
ÀH`%x'@, H`%X'
Â@Print an integer as an unsigned hexadecimal number. H`%x'@ uses lower-case letters and H`%X'@ uses upper-case. See section ‰ŠP�”›Integer Conversions@�”˜, for details.
ÀH`%f'
Â@Print a floating-point number in normal (fixed-point) notation. See section ‰ŠP�”›Floating-Point Conversions@�”˜, for details.
ÀH`%e'@, H`%E'
Â@Print a floating-point number in exponential notation. H`%e'@ uses lower-case letters and H`%E'@ uses upper-case. See section ‰ŠP�”›Floating-Point Conversions@�”˜, for details.
ÀH`%g'@, H`%G'
Â@Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. H`%g'@ uses lower-case letters and H`%G'@ uses upper-case. See section ‰ŠP�”›Floating-Point Conversions@�”˜, for details.
ÀH`%c'
Â@Print a single character. See section ‰ŠP�”›Other Output Conversions@�”˜.
ÀH`%s'
Â@Print a string. See section ‰ŠP�”›Other Output Conversions@�”˜.
ÀH`%p'
Â@Print the value of a pointer. See section ‰ŠP�”›Other Output Conversions@�”˜.
ÀH`%n'
Â@Get the number of characters printed so far. See section ‰ŠP�”›Other Output Conversions@�”˜. Note that this conversion specification never produces any output.
ÀH`%m'
Â@Print the string corresponding to the value of Herrno@. (This is a GNU extension.) See section ‰ŠP�”›Other Output Conversions@�”˜.
ÀH`%%'
Â@Print a literal H`%'@ character. See section ‰ŠP�”›Other Output Conversions@�”˜.À

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.
ˆ‰SEC91ŠT�”›Integer Conversions

@�”˜This section describes the options for the H`%d'@, H`%i'@, H`%o'@, H`%u'@, H`%x'@, and H`%X'@ conversion specifications. These conversions print integers in various formats.
The H`%d'@ and H`%i'@ conversion specifications both print an Hint@ argument as a signed decimal number; while H`%o'@, H`%u'@, and H`%x'@ print the argument as an unsigned octal, decimal, or hexadecimal number (respectively). The H`%X'@ conversion specification is just like H`%x'@ except that it uses the characters H`ABCDEF'@ as digits instead of H`abcdef'@.
The following flags are meaningful:
H`-'
Â@Left-justify the result in the field (instead of the normal right-justification).
ÀH`+'
Â@For the signed H`%d'@ and H`%i'@ conversions, print a plus sign if the value is positive.
ÀH` '
Â@For the signed H`%d'@ and H`%i'@ conversions, if the result doesn't start with a plus or minus sign, prefix it with a space character instead. Since the H`+'@ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
ÀH`#'
Â@For the H`%o'@ conversion, this forces the leading digit to be H`0'@, as if by increasing the precision. For H`%x'@ or H`%X'@, this prefixes a leading H`0x'@ or H`0X'@ (respectively) to the result. This doesn't do anything useful for the H`%d'@, H`%i'@, or H`%u'@ conversions. Using this flag produces output which can be parsed by the Hstrtoul@ function (see section ‰ŠP�”›Parsing of Integers@�”˜) and Hscanf@ with the H`%i'@ conversion (see section ‰ŠP�”›Numeric Input Conversions@�”˜).
ÀH`''
Â@Separate the digits into groups as specified by the locale specified for the HLC_NUMERIC@ category; see section ‰ŠP�”›Generic Numeric Formatting Parameters@�”˜. This flag is a GNU extension.
ÀH`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 H`-'@ 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 an explicit precision of zero, then no characters at all are produced.
Without a type modifier, the corresponding argument is treated as an Hint@ (for the signed conversions H`%i'@ and H`%d'@) or Hunsigned int@ (for the unsigned conversions H`%o'@, H`%u'@, H`%x'@, and H`%X'@). Recall that since Hprintf@ and friends are variadic, any Hchar@ and Hshort@ arguments are automatically converted to Hint@ by the default argument promotions. For arguments of other integer types, you can use these modifiers:
H`h'
Â@Specifies that the argument is a Hshort int@ or Hunsigned short int@, as appropriate. A Hshort@ argument is converted to an Hint@ or Hunsigned int@ by the default argument promotions anyway, but the H`h'@ modifier says to convert it back to a Hshort@ again.
ÀH`l'
Â@Specifies that the argument is a Hlong int@ or Hunsigned long int@, as appropriate. Two H`l'@ characters is like the H`L'@ modifier, below.
ÀH`L'
Â
ÀH`ll'
Â
ÀH`q'
Â@Specifies that the argument is a Hlong 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 Hlong int@.) The H`q'@ modifier is another name for the same thing, which comes from 4.4 BSD; a Hlong long int@ is sometimes called a "quad" Hint@.
ÀH`Z'
Â@Specifies that the argument is a Hsize_t@. This is a GNU extension.À

Here is an 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 H`%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|
ˆ‰SEC92ŠT�”›Floating-Point Conversions

@�”˜This section discusses the conversion specifications for floating-point numbers: the H`%f'@, H`%e'@, H`%E'@, H`%g'@, and H`%G'@ conversions.
The H`%f'@ conversion prints its argument in fixed-point notation, producing output of the form [H-@]BdddH.Bddd@, where the number of digits following the decimal point is controlled by the precision you specify.
The H`%e'@ conversion prints its argument in exponential notation, producing output of the form [H-@]BdH.BdddHe@[H+@|H-@]Bdd@. Again, the number of digits following the decimal point is controlled by the precision. The exponent always contains at least two digits. The H`%E'@ conversion is similar but the exponent is marked with the letter H`E'@ instead of H`e'@.
The H`%g'@ and H`%G'@ conversions print the argument in the style of H`%e'@ or H`%E'@ (respectively) if the exponent would be less than -4 or greater than or equal to the precision; otherwise they use the H`%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:
H`-'
Â@Left-justify the result in the field. Normally the result is right-justified.
ÀH`+'
Â@Always include a plus or minus sign in the result.
ÀH` '
Â@If the result doesn't start with a plus or minus sign, prefix it with a space instead. Since the H`+'@ flag ensures that the result includes a sign, this flag is ignored if you supply both of them.
ÀH`#'
Â@Specifies that the result should always include a decimal point, even if no digits follow it. For the H`%g'@ and H`%G'@ conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed.
ÀH`''
Â@Separate the digits of the integer part of the result into groups as specified by the locale specified for the HLC_NUMERIC@ category; see section ‰ŠP�”›Generic Numeric Formatting Parameters@�”˜. This flag is a GNU extension.
ÀH`0'
Â@Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the H`-'@ flag is also specified.À

The precision specifies how many digits follow the decimal-point character for the H`%f'@, H`%e'@, and H`%E'@ conversions. For these conversions, the default precision is H6@. If the precision is explicitly H0@, this suppresses the decimal point character entirely. For the H`%g'@ and H`%G'@ conversions, the precision specifies how many significant digits to print. Significant digits are the first digit before the decimal point, and all the digits after it. If the precision H0@ or not specified for H`%g'@ or H`%G'@, it is treated like a value of H1@. If the value being printed cannot be expressed accurately in the specified number of digits, the value is rounded to the nearest number that fits.
Without a type modifier, the floating-point conversions use an argument of type Hdouble@. (By the default argument promotions, any Hfloat@ arguments are automatically converted to Hdouble@.) The following type modifier is supported:
H`L'
Â@An uppercase H`L'@ specifies that the argument is a Hlong 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 H`%g'@ conversion drops trailing zeros.
ˆ‰SEC93ŠT�”›Other Output Conversions

@�”˜This section describes miscellaneous conversions for Hprintf@.
The H`%c'@ conversion prints a single character. The Hint@ argument is first converted to an Hunsigned char@. The H`-'@ 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 H`hello'@.
The H`%s'@ conversion prints a string. The corresponding argument must be of type Hchar *@ (or Hconst 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 H`-'@ 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 H` nowhere '@.
If you accidentally pass a null pointer as the argument for a H`%s'@ conversion, the GNU library prints it as H`(null)'@. We think this is more useful than crashing. But it's not good practice to pass a null argument intentionally.
The H`%m'@ conversion prints the string corresponding to the error code in Herrno@. See section ‰ŠP�”›Error Messages@�”˜. Thus: fprintf (stderr, "can't open `%s': %m\n", filename);
is equivalent to: fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
The H`%m'@ conversion is a GNU C library extension.
The H`%p'@ conversion prints a pointer value. The corresponding argument must be of type Hvoid *@. In practice, you can use any type of pointer.
In the GNU system, non-null pointers are printed as unsigned integers, as if a H`%#x'@ conversion were used. Null pointers print as H`(nil)'@. (Pointers might print differently in other systems.)
For example: printf ("%p", "testing");
prints H`0x'@ followed by a hexadecimal number--the address of the string constant H"testing"@. It does not print the word H`testing'@.
You can supply the H`-'@ flag with the H`%p'@ conversion to specify left-justification, but no other flags, precision, or type modifiers are defined.
The H`%n'@ conversion is unlike any of the other output conversions. It uses an argument which must be a pointer to an Hint@, but instead of printing anything it stores the number of characters printed so far by this call at that location. The H`h'@ and H`l'@ type modifiers are permitted to specify that the argument is of type Hshort int *@ or Hlong int *@ instead of Hint *@, 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 Hnchar@ to H7@, because H`3 bears'@ is seven characters.
The H`%%'@ conversion prints a literal H`%'@ character. This conversion doesn't use an argument, and no flags, field width, precision, or type modifiers are permitted.
ˆ‰SEC94ŠT�”›Formatted Output Functions

@�”˜This section describes how to call Hprintf@ and related functions. Prototypes for these functions are in the header file H`stdio.h'@. Because these functions take a variable number of arguments, you Bmust@ declare prototypes for them before using them. Of course, the easiest way to make sure you have all the right prototypes is to just include H`stdio.h'@. ‰IDX490Š

A�”˜Function:@ int Dprintf@ B(const char *Btemplate@, ...)
Â‰IDX491Š@�”˜The Hprintf@ function prints the optional arguments under the control of the template string Btemplate@ to the stream Hstdout@. It returns the number of characters printed, or a negative value if there was an output error.À

AFunction:@ int Dfprintf@ B(FILE *Bstream@, const char *Btemplate@, ...)
Â‰IDX492Š@�”˜This function is just like Hprintf@, except that the output is written to the stream Bstream@ instead of Hstdout@.À

AFunction:@ int Dsprintf@ B(char *Bs@, const char *Btemplate@, ...)
Â‰IDX493Š@�”˜This is like Hprintf@, except that the output is stored in the character array Bs@ instead of written to a stream. A null character is written to mark the end of the string.
The Hsprintf@ function returns the number of characters stored in the array Bs@, not including the terminating null character.
The behavior of this function is undefined if copying takes place between objects that overlap--for example, if Bs@ is also given as an argument to be printed under control of the H`%s'@ conversion. See section ‰ŠP�”›Copying and Concatenation@�”˜.
DWarning:@ The Hsprintf@ function can be Ddangerous@ because it can potentially output more characters than can fit in the allocation size of the string Bs@. Remember that the field width given in a conversion specification is only a Bminimum@ value.
To avoid this problem, you can use Hsnprintf@ or Hasprintf@, described below.À

AFunction:@ int Dsnprintf@ B(char *Bs@, size_t Bsize@, const char *Btemplate@, ...)
Â‰IDX494Š@�”˜The Hsnprintf@ function is similar to Hsprintf@, except that the Bsize@ argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least Bsize@ characters for the string Bs@.
The return value is the number of characters stored, not including the terminating null. If this value equals JsizeH - 1@, then there was not enough space in Bs@ for all the output. You should try again with a bigger output string. Here is an example of doing this: /* Construct a message describing the value of a variable
whose name is Bname@ and whose value is Bvalue@. */
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 Hasprintf@, below.À

ˆ‰SEC95ŠT�”›Dynamically Allocating Formatted Output

@�”˜The functions in this section do formatted output and place the results in dynamically allocated memory.

AFunction:@ int Dasprintf@ B(char **Bptr@, const char *Btemplate@, ...)
Â‰IDX495Š@�”˜This function is similar to Hsprintf@, except that it dynamically allocates a string (as with Hmalloc@; see section ‰ŠP�”›Unconstrained Allocation@�”˜) to hold the output, instead of putting the output in a buffer you allocate in advance. The Bptr@ argument should be the address of a Hchar *@ object, and Hasprintf@ stores a pointer to the newly allocated string at that location.
Here is how to use Hasprintf@ to get the same result as the Hsnprintf@ example, but more easily: /* Construct a message describing the value of a variable
whose name is Bname@ and whose value is Bvalue@. */
char *
make_message (char *name, char *value)
{
char *result;
asprintf (&result, "value of %s is %s", name, value);
return result;
} À

AFunction:@ int Dobstack_printf@ B(struct obstack *Bobstack@, const char *Btemplate@, ...)
Â‰IDX496Š@�”˜This function is similar to Hasprintf@, except that it uses the obstack Bobstack@ to allocate the space. See section ‰ŠP�”›Obstacks@�”˜.
The characters are written onto the end of the current object. To get at them, you must finish the object with Hobstack_finish@ (see section ‰ŠP�”›Growing Objects@�”˜).À

ˆ‰SEC96ŠT�”›Variable Arguments Output Functions

@�”˜The functions Hvprintf@ and friends are provided so that you can define your own variadic Hprintf@-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 Hprintf@ 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 Hvprintf@ series, which lets you pass a Hva_list@ to describe "all of my arguments after the first five."
When it is sufficient to define a macro rather than a real function, the GNU C compiler provides a way to do this much more easily with macros. For example: #define myprintf(a, b, c, d, e, rest...) printf (mytemplate , ## rest...)
See section `Macros with Variable Numbers of Arguments' in BUsing GNU CC@, for details. But this is limited to macros, and does not apply to real functions at all.
Before calling Hvprintf@ or the other functions listed in this section, you Bmust@ call Hva_start@ (see section ‰ŠP�”›Variadic Functions@�”˜) to initialize a pointer to the variable arguments. Then you can call Hva_arg@ to fetch the arguments that you want to handle yourself. This advances the pointer past those arguments.
Once your Hva_list@ pointer is pointing at the argument of your choice, you are ready to call Hvprintf@. That argument and all subsequent arguments that were passed to your function are used by Hvprintf@ along with the template that you specified separately.
In some other systems, the Hva_list@ pointer may become invalid after the call to Hvprintf@, so you must not use Hva_arg@ after you call Hvprintf@. Instead, you should call Hva_end@ to retire the pointer from service. However, you can safely call Hva_start@ on another pointer variable and begin fetching the arguments again through that pointer. Calling Hvprintf@ does not destroy the argument list of your function, merely the particular pointer that you passed to it.
GNU C does not have such restrictions. You can safely continue to fetch arguments from a Hva_list@ pointer after passing it to Hvprintf@, and Hva_end@ is a no-op. (Note, however, that subsequent Hva_arg@ calls will fetch the same arguments which Hvprintf@ previously used.)
Prototypes for these functions are declared in H`stdio.h'@. ‰IDX497Š

A�”˜Function:@ int Dvprintf@ B(const char *Btemplate@, va_list Bap@)
Â‰IDX498Š@�”˜This function is similar to Hprintf@ except that, instead of taking a variable number of arguments directly, it takes an argument list pointer Bap@.À

AFunction:@ int Dvfprintf@ B(FILE *Bstream@, const char *Btemplate@, va_list Bap@)
Â‰IDX499Š@�”˜This is the equivalent of Hfprintf@ with the variable argument list specified directly as for Hvprintf@.À

AFunction:@ int Dvsprintf@ B(char *Bs@, const char *Btemplate@, va_list Bap@)
Â‰IDX500Š@�”˜This is the equivalent of Hsprintf@ with the variable argument list specified directly as for Hvprintf@.À

AFunction:@ int Dvsnprintf@ B(char *Bs@, size_t Bsize@, const char *Btemplate@, va_list Bap@)
Â‰IDX501Š@�”˜This is the equivalent of Hsnprintf@ with the variable argument list specified directly as for Hvprintf@.À

AFunction:@ int Dvasprintf@ B(char **Bptr@, const char *Btemplate@, va_list Bap@)
Â‰IDX502Š@�”˜The Hvasprintf@ function is the equivalent of Hasprintf@ with the variable argument list specified directly as for Hvprintf@.À

AFunction:@ int Dobstack_vprintf@ B(struct obstack *Bobstack@, const char *Btemplate@, va_list Bap@)
Â‰IDX503Š@�”˜The Hobstack_vprintf@ function is the equivalent of Hobstack_printf@ with the variable argument list specified directly as for Hvprintf@.À

Here's an example showing how you might use Hvfprintf@. This is a function that prints error messages to the stream Hstderr@, along with a prefix indicating the name of the program (see section ‰ŠP�”›Error Messages@�”˜, for a description of Hprogram_invocation_short_name@). #include <stdio.h>
#include <stdarg.h>

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

fprintf (stderr, "%s: ", program_invocation_short_name);
va_start (ap, count);
vfprintf (stderr, template, ap);
va_end (ap);
}
You could call Heprintf@ like this: eprintf ("file `%s' does not exist\n", filename);
In GNU C, there is a special construct you can use to let the compiler know that a function uses a Hprintf@-style format string. Then it can check the number and types of arguments in each call to the function, and warn you when they do not match the format string. For example, take this declaration of Heprintf@: void eprintf (const char *template, ...)
__attribute__ ((format (printf, 1, 2)));
This tells the compiler that Heprintf@ uses a format string like Hprintf@ (as opposed to Hscanf@; see section ‰ŠP�”›Formatted Input@�”˜); the format string appears as the first argument; and the arguments to satisfy the format begin with the second. See section `Declaring Attributes of Functions' in BUsing GNU CC@, for more information.
ˆ‰SEC97ŠT�”›Parsing a Template String

‰IDX504Š
@�”˜You can use the function Hparse_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 Hprintf@ to avoid passing along invalid arguments from the user's program, which could cause a crash.
All the symbols described in this section are declared in the header file H`printf.h'@.

AFunction:@ size_t Dparse_printf_format@ B(const char *Btemplate@, size_t Bn@, int *Bargtypes@)
Â‰IDX505Š@�”˜This function returns information about the number and types of arguments expected by the Hprintf@ template string Btemplate@. The information is stored in the array Bargtypes@; each element of this array describes one argument. This information is encoded using the various H`PA_'@ macros, listed below.
The Bn@ argument specifies the number of elements in the array Bargtypes@. This is the most elements that Hparse_printf_format@ will try to write.
Hparse_printf_format@ returns the total number of arguments required by Btemplate@. If this number is greater than Bn@, then the information returned describes only the first Bn@ arguments. If you want information about more than that many arguments, allocate a bigger array and call Hparse_printf_format@ again.À

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

AMacro:@ int DPA_FLAG_MASK
Â‰IDX506Š@�”˜This macro is a bitmask for the type modifier flag bits. You can write the expression H(argtypes[i] & PA_FLAG_MASK)@ to extract just the flag bits for an argument, or H(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.
HPA_INT
Â‰IDX507Š@�”˜This specifies that the base type is Hint@.
ÀHPA_CHAR
Â‰IDX508Š@�”˜This specifies that the base type is Hint@, cast to Hchar@.
ÀHPA_STRING
Â‰IDX509Š@�”˜This specifies that the base type is Hchar *@, a null-terminated string.
ÀHPA_POINTER
Â‰IDX510Š@�”˜This specifies that the base type is Hvoid *@, an arbitrary pointer.
ÀHPA_FLOAT
Â‰IDX511Š@�”˜This specifies that the base type is Hfloat@.
ÀHPA_DOUBLE
Â‰IDX512Š@�”˜This specifies that the base type is Hdouble@.
ÀHPA_LAST
Â‰IDX513Š@�”˜You can define additional base types for your own programs as offsets from HPA_LAST@. For example, if you have data types H`foo'@ and H`bar'@ with their own specialized Hprintf@ 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.
HPA_FLAG_PTR
Â‰IDX514Š@�”˜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, H`PA_INT|PA_FLAG_PTR'@ represents the type H`int *'@.
ÀHPA_FLAG_SHORT
Â‰IDX515Š@�”˜If this bit is set, it indicates that the base type is modified with Hshort@. (This corresponds to the H`h'@ type modifier.)
ÀHPA_FLAG_LONG
Â‰IDX516Š@�”˜If this bit is set, it indicates that the base type is modified with Hlong@. (This corresponds to the H`l'@ type modifier.)
ÀHPA_FLAG_LONG_LONG
Â‰IDX517Š@�”˜If this bit is set, it indicates that the base type is modified with Hlong long@. (This corresponds to the H`L'@ type modifier.)
ÀHPA_FLAG_LONG_DOUBLE
Â‰IDX518Š@�”˜This is a synonym for HPA_FLAG_LONG_LONG@, used by convention with a base type of HPA_DOUBLE@ to indicate a type of Hlong double@.À

ˆ‰SEC98ŠT�”›Example of Parsing a Template String

@�”˜Here is an example of decoding argument types for a format string. We assume this is part of an interpreter which contains arguments of type HNUMBER@, HCHAR@, HSTRING@ and HSTRUCTURE@ (and perhaps others which are not valid here). /* Test whether the Bnargs@ specified objects
in the vector Bargs@ are valid
for the format string Bformat@:
if so, return 1.
If not, return 0 after printing an error message. */

int
validate_args (char *format, int nargs, OBJECT *args)
{
int *argtypes;
int nwanted;

/* Get the information about the arguments.
Each conversion specification must be at least two characters
long, so there cannot be more specifications than half the
length of the string. */

argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
nwanted = parse_printf_format (string, nelts, argtypes);

/* Check the number of arguments. */
if (nwanted > nargs)
{
error ("too few arguments (at least %d required)", nwanted);
return 0;
}

/* Check the C type wanted for each argument
and see if the object given is suitable. */
for (i = 0; i < nwanted; i++)
{
int wanted;

if (argtypes[i] & PA_FLAG_PTR)
wanted = STRUCTURE;
else
switch (argtypes[i] & ~PA_FLAG_MASK)
{
case PA_INT:
case PA_FLOAT:
case PA_DOUBLE:
wanted = NUMBER;
break;
case PA_CHAR:
wanted = CHAR;
break;
case PA_STRING:
wanted = STRING;
break;
case PA_POINTER:
wanted = STRUCTURE;
break;
}
if (TYPE (args[i]) != wanted)
{
error ("type mismatch for arg number %d", i);
return 0;
}
}
return 1;
}
ˆ‰SEC99Št�”›Customizing |printf

‰IDX519Š‰IDX520Š‰IDX521Š
@�”˜The GNU C library lets you define your own custom conversion specifiers for Hprintf@ template strings, to teach Hprintf@ clever ways to print the important data structures of your program.
The way you do this is by registering the conversion with the function Hregister_printf_function@; see section ‰ŠP�”›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 section ‰ŠP�”›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 section ‰ŠP�”›Parsing a Template String@�”˜, for information about this.
The facilities of this section are declared in the header file H`printf.h'@.
DPortability Note:@ The ability to extend the syntax of Hprintf@ template strings is a GNU extension. ISO standard C has nothing similar.
ˆ‰SEC100ŠT�”›Registering New Conversions

@�”˜The function to register a new output conversion is Hregister_printf_function@, declared in H`printf.h'@. ‰IDX522Š

A�”˜Function:@ int Dregister_printf_function@ B(int Bspec@, printf_function Bhandler-function@, printf_arginfo_function Barginfo-function@)
Â‰IDX523Š@�”˜This function defines the conversion specifier character Bspec@. Thus, if Bspec@ is H'z'@, it defines the conversion H`%z'@. You can redefine the built-in conversions like H`%s'@, but flag characters like H`#'@ and type modifiers like H`l'@ can never be used as conversions; calling Hregister_printf_function@ for those characters has no effect.
The Bhandler-function@ is the function called by Hprintf@ and friends when this conversion appears in a template string. See section ‰ŠP�”›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 Bspec@ is removed.
The Barginfo-function@ is the function called by Hparse_printf_format@ when this conversion appears in a template string. See section ‰ŠP�”›Parsing a Template String@�”˜, for information about this.
DAttention:@ In the GNU C library version before 2.0 the Barginfo-function@ function did not need to be installed unless the user uses the Hparse_printf_format@ function. This changed. Now a call to any of the Hprintf@ functions will call this function when this format specifier appears in the format string.
The return value is H0@ on success, and H-1@ on failure (which occurs if Bspec@ 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.À

ˆ‰SEC101ŠT�”›Conversion Specifier Options

@�”˜If you define a meaning for H`%A'@, what if the template contains H`%+23A'@ or H`%-#A'@? 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 Bhandler-function@ and Barginfo-function@ arguments to Hregister_printf_function@ accept an argument that points to a Hstruct printf_info@, which contains information about the options appearing in an instance of the conversion specifier. This data type is declared in the header file H`printf.h'@. ‰IDX524Š

A�”˜Type:@ Dstruct printf_info
Â‰IDX525Š@�”˜This structure is used to pass information about the options appearing in an instance of a conversion specifier in a Hprintf@ template string to the handler and arginfo functions for that specifier. It contains the following members:
Hint prec
Ä@This is the precision specified. The value is H-1@ if no precision was specified. If the precision was given as H`*'@, the Hprintf_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 HINT_MIN@, since the actual value is not known.
ÂHint width
Ä@This is the minimum field width specified. The value is H0@ if no width was specified. If the field width was given as H`*'@, the Hprintf_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 HINT_MIN@, since the actual value is not known.
ÂHwchar_t 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.
ÂHunsigned int is_long_double
Ä@This is a boolean that is true if the H`L'@, H`ll'@, or H`q'@ type modifier was specified. For integer conversions, this indicates Hlong long int@, as opposed to Hlong double@ for floating point conversions.
ÂHunsigned int is_short
Ä@This is a boolean that is true if the H`h'@ type modifier was specified.
ÂHunsigned int is_long
Ä@This is a boolean that is true if the H`l'@ type modifier was specified.
ÂHunsigned int alt
Ä@This is a boolean that is true if the H`#'@ flag was specified.
ÂHunsigned int space
Ä@This is a boolean that is true if the H` '@ flag was specified.
ÂHunsigned int left
Ä@This is a boolean that is true if the H`-'@ flag was specified.
ÂHunsigned int showsign
Ä@This is a boolean that is true if the H`+'@ flag was specified.
ÂHunsigned int group
Ä@This is a boolean that is true if the H`''@ flag was specified.
ÂHunsigned int extra
Ä@This flag has a special meaning depending on the context. It could be used freely by the user-defined handlers but when called from the Hprintf@ function this variable always contains the value H0@.
ÂHwchar_t pad
Ä@This is the character to use for padding the output to the minimum field width. The value is H'0'@ if the H`0'@ flag was specified, and H' '@ otherwise.Â
À

ˆ‰SEC102ŠT�”›Defining the Output Handler

@�”˜Now let's look at how to define the handler and arginfo functions which are passed as arguments to Hregister_printf_function@.
DCompatibility Note:@ The interface change in the GNU libc version 2.0. Previously the third argument was of type Hva_list *@.
You should define your handler functions with a prototype like: int Bfunction@ (FILE *stream, const struct printf_info *info,
const void *const *args)
The Bstream@ argument passed to the handler function is the stream to which it should write output.
The Binfo@ 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 section ‰ŠP�”›Conversion Specifier Options@�”˜, for a description of this data structure.
The Bargs@ is a vector of pointers to the arguments data. The number of arguments were determined by calling the argument information function provided by the user.
Your handler function should return a value just like Hprintf@ does: it should return the number of characters it has written, or a negative value to indicate an error.

AData Type:@ Dprintf_function
Â‰IDX526Š@�”˜This is the data type that a handler function should have.À

If you are going to use Hparse_printf_format@ in your application, you must also define a function to pass as the Barginfo-function@ argument for each new conversion you install with Hregister_printf_function@.
You have to define these functions with a prototype like: int Bfunction@ (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. The function should also fill in no more than Bn@ elements of the Bargtypes@ array with information about the types of each of these arguments. This information is encoded using the various H`PA_'@ macros. (You will notice that this is the same calling convention Hparse_printf_format@ itself uses.)

AData Type:@ Dprintf_arginfo_function
Â‰IDX527Š@�”˜This type is used to describe functions that return information about the number and type of arguments used by a conversion specifier.À

ˆ‰SEC103Š\�”›printfT Extension Example

@�”˜Here is an example showing how to define a Hprintf@ handler function. This program defines a data structure called a HWidget@ and defines the H`%W'@ conversion to print information about HWidget *@ arguments, including the pointer value and the name stored in the data structure. The H`%W'@ conversion supports the minimum field width and left-justification options, but ignores everything else. #include <stdio.h>
#include <printf.h>
#include <stdarg.h>

typedef struct
{
char *name;
} Widget;

int
print_widget (FILE *stream, const struct printf_info *info, va_list *app)
{
Widget *w;
char *buffer;
int len;

/* Format the output into a string. */
w = va_arg (*app, Widget *);
len = asprintf (&buffer, "<Widget %p: %s>", w, w->name);
if (len == -1)
return -1;

/* Pad to the minimum field width and print to the stream. */
len = fprintf (stream, "%*s",
(info->left ? - info->width : info->width),
buffer);

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

int
print_widget_arginfo (const struct printf_info *info, size_t n,
int *argtypes)
{
/* We always take exactly one argument and this is a pointer to the
structure.. */
if (n > 0)
argtypes[0] = PA_POINTER;
return 1;
}

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

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

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

return 0;
}
The output produced by this program looks like: |<Widget 0xffeffb7c: mywidget>|
| <Widget 0xffeffb7c: mywidget>|
|<Widget 0xffeffb7c: mywidget> |
ˆ‰SEC104Št�”›Formatted Input

‰IDX528Š‰IDX529Š‰IDX530Š‰IDX531Š@�”˜The functions described in this section (Hscanf@ 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 Bformat string@ or Btemplate string@.
ˆ‰SEC105ŠT�”›Formatted Input Basics

@�”˜Calls to Hscanf@ are superficially similar to calls to Hprintf@ 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 Hprintf@, the interpretation of the template is oriented more towards free-format input and simple pattern matching, rather than fixed-field formatting. For example, most Hscanf@ conversions skip over any amount of "white space" (including spaces, tabs, and 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. Ordinarily, 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. ‰IDX532Š
@�”˜Another area of difference between Hscanf@ and Hprintf@ is that you must remember to supply pointers rather than immediate values as the optional arguments to Hscanf@; 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 Hscanf@, you might want to double-check this.
When a Bmatching failure@ occurs, Hscanf@ returns immediately, leaving the first non-matching character as the next character to be read from the stream. The normal return value from Hscanf@ 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. ‰IDX533Š
@�”˜The Hscanf@ function is typically used for things like reading in the contents of tables. For example, here is a function that uses Hscanf@ to initialize an array of Hdouble@: void
readarray (double *array, int n)
{
int i;
for (i=0; i<n; i++)
if (scanf (" %lf", &(array[i])) != 1)
invalid_input_error ();
}
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 Flex to generate a lexical scanner, or Bison to generate a parser, rather than using Hscanf@. For more information about these tools, see section `' in BFlex: The Lexical Scanner Generator@, and section `' in BThe Bison Reference Manual@.
ˆ‰SEC106ŠT�”›Input Conversion Syntax

@�”˜A Hscanf@ template string is a string that contains ordinary multibyte characters interspersed with conversion specifications that start with H`%'@.
Any whitespace character (as defined by the Hisspace@ function; see section ‰ŠP�”›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 H` , '@ 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 Hscanf@ template string have the general form: % Bflags@ Bwidth@ Btype@ Bconversion@
In more detail, an input conversion specification consists of an initial H`%'@ character followed in sequence by: þÂ
• An optional Bflag character@ H`*'@, which says to ignore the text read for this specification. When Hscanf@ finds a conversion specification that uses this flag, it reads input as directed by the rest of the conversion specification, but it discards this input, does not use a pointer argument, and does not increment the count of successful assignments. ‰IDX534Š
• @�”˜An optional flag character H`a'@ (valid with string conversions only) which requests allocation of a buffer long enough to store the string in. (This is a GNU extension.) See section ‰ŠP�”›Dynamically Allocating String Conversions@�”˜.
• An optional decimal integer that specifies the Bmaximum 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. String input conversions store a null character to mark the end of the input; the maximum field width does not include this terminator. ‰IDX535Š
• @�”˜An optional Btype modifier character@. For example, you can specify a type modifier of H`l'@ with integer conversions such as H`%d'@ to specify that the argument is a pointer to a Hlong int@ rather than a pointer to an Hint@. ‰IDX536Š
• @�”˜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 allow.
With the H`-Wformat'@ option, the GNU C compiler checks calls to Hscanf@ and related functions. It examines the format string and verifies that the correct number and types of arguments are supplied. There is also a GNU C syntax to tell the compiler that a function you write uses a Hscanf@-style format string. See section `Declaring Attributes of Functions' in BUsing GNU CC@, for more information.
ˆ‰SEC107ŠT�”›Table of Input Conversions

‰IDX537Š
@�”˜Here is a table that summarizes the various conversion specifications:
H`%d'
Â@Matches an optionally signed integer written in decimal. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%i'
Â@Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%o'
Â@Matches an unsigned integer written in octal radix. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%u'
Â@Matches an unsigned integer written in decimal radix. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%x'@, H`%X'
Â@Matches an unsigned integer written in hexadecimal radix. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%e'@, H`%f'@, H`%g'@, H`%E'@, H`%G'
Â@Matches an optionally signed floating-point number. See section ‰ŠP�”›Numeric Input Conversions@�”˜.
ÀH`%s'
Â@Matches a string containing only non-whitespace characters. See section ‰ŠP�”›String Input Conversions@�”˜.
ÀH`%['
Â@Matches a string of characters that belong to a specified set. See section ‰ŠP�”›String Input Conversions@�”˜.
ÀH`%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 section ‰ŠP�”›String Input Conversions@�”˜.
ÀH`%p'
Â@Matches a pointer value in the same implementation-defined format used by the H`%p'@ output conversion for Hprintf@. See section ‰ŠP�”›Other Input Conversions@�”˜.
ÀH`%n'
Â@This conversion doesn't read any characters; it records the number of characters read so far by this call. See section ‰ŠP�”›Other Input Conversions@�”˜.
ÀH`%%'
Â@This matches a literal H`%'@ character in the input stream. No corresponding argument is used. See section ‰ŠP�”›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, extra arguments are simply ignored.
ˆ‰SEC108ŠT�”›Numeric Input Conversions

@�”˜This section describes the Hscanf@ conversions for reading numeric values.
The H`%d'@ conversion matches an optionally signed integer in decimal radix. The syntax that is recognized is the same as that for the Hstrtol@ function (see section ‰ŠP�”›Parsing of Integers@�”˜) with the value H10@ for the Bbase@ argument.
The H`%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 Hstrtol@ function (see section ‰ŠP�”›Parsing of Integers@�”˜) with the value H0@ for the Bbase@ argument. (You can print integers in this syntax with Hprintf@ by using the H`#'@ flag character with the H`%x'@, H`%o'@, or H`%d'@ conversion. See section ‰ŠP�”›Integer Conversions@�”˜.)
For example, any of the strings H`10'@, H`0xa'@, or H`012'@ could be read in as integers under the H`%i'@ conversion. Each of these specifies a number with decimal value H10@.
The H`%o'@, H`%u'@, and H`%x'@ conversions match unsigned integers in octal, decimal, and hexadecimal radices, respectively. The syntax that is recognized is the same as that for the Hstrtoul@ function (see section ‰ŠP�”›Parsing of Integers@�”˜) with the appropriate value (H8@, H10@, or H16@) for the Bbase@ argument.
The H`%X'@ conversion is identical to the H`%x'@ conversion. They both permit either uppercase or lowercase letters to be used as digits.
The default type of the corresponding argument for the H%d@ and H%i@ conversions is Hint *@, and Hunsigned int *@ for the other integer conversions. You can use the following type modifiers to specify other sizes of integer:
H`h'
Â@Specifies that the argument is a Hshort int *@ or Hunsigned short int *@.
ÀH`l'
Â@Specifies that the argument is a Hlong int *@ or Hunsigned long int *@. Two H`l'@ characters is like the H`L'@ modifier, below.
ÀH`ll'
Â
ÀH`L'
Â
ÀH`q'
Â@Specifies that the argument is a Hlong long int *@ or Hunsigned long long int *@. (The Hlong 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 Hlong int@.) The H`q'@ modifier is another name for the same thing, which comes from 4.4 BSD; a Hlong long int@ is sometimes called a "quad" Hint@.À

All of the H`%e'@, H`%f'@, H`%g'@, H`%E'@, and H`%G'@ input conversions are interchangeable. They all match an optionally signed floating point number, in the same syntax as for the Hstrtod@ function (see section ‰ŠP�”›Parsing of Floats@�”˜).
For the floating-point input conversions, the default argument type is Hfloat *@. (This is different from the corresponding output conversions, where the default type is Hdouble@; remember that Hfloat@ arguments to Hprintf@ are converted to Hdouble@ by the default argument promotions, but Hfloat *@ arguments are not promoted to Hdouble *@.) You can specify other sizes of float using these type modifiers:
H`l'
Â@Specifies that the argument is of type Hdouble *@.
ÀH`L'
Â@Specifies that the argument is of type Hlong double *@.À

For all the above number parsing formats there is an additional optional flag H`''@. When this flag is given the Hscanf@ function expects the number represented in the input string to be formatted according to the grouping rules of the currently selected locale (see section ‰ŠP�”›Generic Numeric Formatting Parameters@�”˜).
If the H"C"@ or H"POSIX"@ locale is selected there is no difference. But for a locale which specifies values for the appropriate fields in the locale the input must have the correct form in the input. Otherwise the longest prefix with a correct form is processed.
ˆ‰SEC109ŠT�”›String Input Conversions

@�”˜This section describes the Hscanf@ input conversions for reading string and character values: H`%s'@, H`%['@, and H`%c'@.
You have two options for how to receive the input from these conversions: þÂ
• Provide a buffer to store it in. This is the default. You should provide an argument of type Hchar *@. DWarning:@ To make a robust program, you must make sure that the input (plus its terminating null) cannot possibly exceed the size of the buffer you provide. In general, the only way to do this is to specify a maximum field width one less than the buffer size. DIf you provide the buffer, always specify a maximum field width to prevent overflow.@
• Ask Hscanf@ to allocate a big enough buffer, by specifying the H`a'@ flag character. This is a GNU extension. You should provide an argument of type Hchar **@ for the buffer address to be stored in. See section ‰ŠP�”›Dynamically Allocating String Conversions@�”˜.Àð
The H`%c'@ conversion is the simplest: it matches a fixed number of characters, always. The maximum field with says how many characters to read; if you don't specify the maximum, the default is 1. This conversion doesn't append a null character to the end of the text it reads. It also does not skip over initial whitespace characters. It reads precisely the next Bn@ characters, and fails if it cannot get that many. Since there is always a maximum field width with H`%c'@ (whether specified, or 1 by default), you can always prevent overflow by making the buffer long enough.
The H`%s'@ conversion matches a string of non-whitespace characters. It skips and discards initial whitespace, but stops when it encounters more whitespace after having read something. It stores a null character at the end of the text that it reads.
For example, reading the input: hello, world
with the conversion H`%10c'@ produces H" hello, wo"@, but reading the same input with the conversion H`%10s'@ produces H"hello,"@.
DWarning:@ If you do not specify a field width for H`%s'@, then the number of characters read is limited only by where the next whitespace character appears. This almost certainly means that invalid input can make your program crash--which is a bug.
To read in characters that belong to an arbitrary set of your choice, use the H`%['@ conversion. You specify the set between the H`['@ character and a following H`]'@ character, using the same syntax used in regular expressions. As special cases: þÂ
• A literal H`]'@ character can be specified as the first character of the set.
• An embedded H`-'@ character (that is, one that is not the first or last character of the set) is used to specify a range of characters.
• If a caret character H`^'@ immediately follows the initial H`['@, then the set of allowed input characters is the everything Bexcept@ the characters listed.Àð
The H`%['@ conversion does not skip over initial whitespace characters.
Here are some examples of H`%['@ conversions and what they mean:
H`%25[1234567890]'
Â@Matches a string of up to 25 digits.
ÀH`%25[][]'
Â@Matches a string of up to 25 square brackets.
ÀH`%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 H`%s'@, because if the input begins with a whitespace character, H`%['@ reports a matching failure while H`%s'@ simply discards the initial whitespace.
ÀH`%25[a-z]'
Â@Matches up to 25 lowercase characters.À

One more reminder: the H`%s'@ and H`%['@ conversions are Ddangerous@ if you don't specify a maximum width or use the H`a'@ flag, 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. A well-written program reports invalid input with a comprehensible error message, not with a crash.
ˆ‰SEC110ŠT�”›Dynamically Allocating String Conversions

@�”˜A GNU extension to formatted input lets you safely read a string with no maximum size. Using this feature, you don't supply a buffer; instead, Hscanf@ allocates a buffer big enough to hold the data and gives you its address. To use this feature, write H`a'@ as a flag character, as in H`%as'@ or H`%a[0-9a-z]'@.
The pointer argument you supply for where to store the input should have type Hchar **@. The Hscanf@ function allocates a buffer and stores its address in the word that the argument points to. You should free the buffer with Hfree@ when you no longer need it.
Here is an example of using the H`a'@ flag with the H`%[...]'@ conversion specification to read a "variable assignment" of the form H`JvariableH = JvalueH'@. {
char *variable, *value;

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

...
}
ˆ‰SEC111ŠT�”›Other Input Conversions

@�”˜This section describes the miscellaneous input conversions.
The H`%p'@ conversion is used to read a pointer value. It recognizes the same syntax as is used by the H`%p'@ output conversion for Hprintf@ (see section ‰ŠP�”›Other Output Conversions@�”˜); that is, a hexadecimal number just as the H`%x'@ conversion accepts. The corresponding argument should be of type Hvoid **@; 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 H`%n'@ conversion produces the number of characters read so far by this call. The corresponding argument should be of type Hint *@. This conversion works in the same way as the H`%n'@ conversion for Hprintf@; see section ‰ŠP�”›Other Output Conversions@�”˜, for an example.
The H`%n'@ conversion is the only mechanism for determining the success of literal matches or conversions with suppressed assignments. If the H`%n'@ follows the locus of a matching failure, then no value is stored for it since Hscanf@ returns before processing the H`%n'@. If you store H-1@ in that argument slot before calling Hscanf@, the presence of H-1@ after Hscanf@ indicates an error occurred before the H`%n'@ was reached.
Finally, the H`%%'@ conversion matches a literal H`%'@ character in the input stream, without using an argument. This conversion does not permit any flags, field width, or type modifier to be specified.
ˆ‰SEC112ŠT�”›Formatted Input Functions

@�”˜Here are the descriptions of the functions for performing formatted input. Prototypes for these functions are in the header file H`stdio.h'@. ‰IDX538Š

A�”˜Function:@ int Dscanf@ B(const char *Btemplate@, ...)
Â‰IDX539Š@�”˜The Hscanf@ function reads formatted input from the stream Hstdin@ under the control of the template string Btemplate@. 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 HEOF@ is returned.À

AFunction:@ int Dfscanf@ B(FILE *Bstream@, const char *Btemplate@, ...)
Â‰IDX540Š@�”˜This function is just like Hscanf@, except that the input is read from the stream Bstream@ instead of Hstdin@.À

AFunction:@ int Dsscanf@ B(const char *Bs@, const char *Btemplate@, ...)
Â‰IDX541Š@�”˜This is like Hscanf@, except that the characters are taken from the null-terminated string Bs@ 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 Bs@ is also given as an argument to receive a string read under control of the H`%s'@ conversion.À

ˆ‰SEC113ŠT�”›Variable Arguments Input Functions

@�”˜The functions Hvscanf@ and friends are provided so that you can define your own variadic Hscanf@-like functions that make use of the same internals as the built-in formatted output functions. These functions are analogous to the Hvprintf@ series of output functions. See section ‰ŠP�”›Variable Arguments Output Functions@�”˜, for important information on how to use them.
DPortability Note:@ The functions listed in this section are GNU extensions.

AFunction:@ int Dvscanf@ B(const char *Btemplate@, va_list Bap@)
Â‰IDX542Š@�”˜This function is similar to Hscanf@ except that, instead of taking a variable number of arguments directly, it takes an argument list pointer Bap@ of type Hva_list@ (see section ‰ŠP�”›Variadic Functions@�”˜).À

AFunction:@ int Dvfscanf@ B(FILE *Bstream@, const char *Btemplate@, va_list Bap@)
Â‰IDX543Š@�”˜This is the equivalent of Hfscanf@ with the variable argument list specified directly as for Hvscanf@.À

AFunction:@ int Dvsscanf@ B(const char *Bs@, const char *Btemplate@, va_list Bap@)
Â‰IDX544Š@�”˜This is the equivalent of Hsscanf@ with the variable argument list specified directly as for Hvscanf@.À

In GNU C, there is a special construct you can use to let the compiler know that a function uses a Hscanf@-style format string. Then it can check the number and types of arguments in each call to the function, and warn you when they do not match the format string. See section `Declaring Attributes of Functions' in BUsing GNU CC@, for details.
ˆ‰SEC114Št�”›End-Of-File and Errors

‰IDX545Š@�”˜Many of the functions described in this chapter return the value of the macro HEOF@ to indicate unsuccessful completion of the operation. Since HEOF@ is used to report both end of file and random errors, it's often better to use the Hfeof@ function to check explicitly for end of file and Hferror@ 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 H`stdio.h'@. ‰IDX546Š

A�”˜Macro:@ int DEOF
Â‰IDX547Š@�”˜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, HEOF@ is H-1@. In other libraries, its value may be some other negative number.À

AFunction:@ void Dclearerr@ B(FILE *Bstream@)
Â‰IDX548Š@�”˜This function clears the end-of-file and error indicators for the stream Bstream@.
The file positioning functions (see section ‰ŠP�”›File Positioning@�”˜) also clear the end-of-file indicator for the stream.À

AFunction:@ int Dfeof@ B(FILE *Bstream@)
Â‰IDX549Š@�”˜The Hfeof@ function returns nonzero if and only if the end-of-file indicator for the stream Bstream@ is set.À

AFunction:@ int Dferror@ B(FILE *Bstream@)
Â‰IDX550Š@�”˜The Hferror@ function returns nonzero if and only if the error indicator for the stream Bstream@ 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 Herrno@ 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 Hfputc@, Hprintf@, and Hfflush@---are implemented in terms of Hwrite@, and all of the Herrno@ error conditions defined for Hwrite@ are meaningful for these functions. For more information about the descriptor-level I/O functions, see section ‰ŠP�”›Low-Level Input/Output@�”˜.
ˆ‰SEC115Št�”›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 ISO C provide for this distinction. This section tells you how to write programs portable to such systems.
‰IDX551Š‰IDX552Š@�”˜When you open a stream, you can specify either a Btext stream@ or a Bbinary stream@. You indicate that you want a binary stream by specifying the H`b'@ modifier in the Bopentype@ argument to Hfopen@; see section ‰ŠP�”›Opening Streams@�”˜. Without this option, Hfopen@ 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 Blines@ which are terminated by newline (H'\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). ‰IDX553Š
• @�”˜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 preceding 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.
ˆ‰SEC116Št�”›File Positioning

‰IDX554Š‰IDX555Š‰IDX556Š
@�”˜The Bfile 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 section ‰ŠP�”›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 Brandom-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 H`stdio.h'@. ‰IDX557Š

A�”˜Function:@ long int Dftell@ B(FILE *Bstream@)
Â‰IDX558Š@�”˜This function returns the current file position of the stream Bstream@.
This function can fail if the stream doesn't support file positioning, or if the file position can't be represented in a Hlong int@, and possibly for other reasons as well. If a failure occurs, a value of H-1@ is returned.À

AFunction:@ int Dfseek@ B(FILE *Bstream@, long int Boffset@, int Bwhence@)
Â‰IDX559Š@�”˜The Hfseek@ function is used to change the file position of the stream Bstream@. The value of Bwhence@ must be one of the constants HSEEK_SET@, HSEEK_CUR@, or HSEEK_END@, to indicate whether the Boffset@ 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 Bstream@ and discards any characters that were "pushed back" by the use of Hungetc@.
Hfseek@ 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.À

DPortability Note:@ In non-POSIX systems, Hftell@ and Hfseek@ might work reliably only on binary streams. See section ‰ŠP�”›Text and Binary Streams@�”˜.
The following symbolic constants are defined for use as the Bwhence@ argument to Hfseek@. They are also used with the Hlseek@ function (see section ‰ŠP�”›Input and Output Primitives@�”˜) and to specify offsets for file locks (see section ‰ŠP�”›Control Operations on Files@�”˜).

AMacro:@ int DSEEK_SET
Â‰IDX560Š@�”˜This is an integer constant which, when used as the Bwhence@ argument to the Hfseek@ function, specifies that the offset provided is relative to the beginning of the file.À

AMacro:@ int DSEEK_CUR
Â‰IDX561Š@�”˜This is an integer constant which, when used as the Bwhence@ argument to the Hfseek@ function, specifies that the offset provided is relative to the current file position.À

AMacro:@ int DSEEK_END
Â‰IDX562Š@�”˜This is an integer constant which, when used as the Bwhence@ argument to the Hfseek@ function, specifies that the offset provided is relative to the end of the file.À

AFunction:@ void Drewind@ B(FILE *Bstream@)
Â‰IDX563Š@�”˜The Hrewind@ function positions the stream Bstream@ at the begining of the file. It is equivalent to calling Hfseek@ on the Bstream@ with an Boffset@ argument of H0L@ and a Bwhence@ argument of HSEEK_SET@, except that the return value is discarded and the error indicator for the stream is reset.À

These three aliases for the H`SEEK_...'@ constants exist for the sake of compatibility with older BSD systems. They are defined in two different header files: H`fcntl.h'@ and H`sys/file.h'@.
HL_SET
Â‰IDX564Š@�”˜An alias for HSEEK_SET@.
ÀHL_INCR
Â‰IDX565Š@�”˜An alias for HSEEK_CUR@.
ÀHL_XTND
Â‰IDX566Š@�”˜An alias for HSEEK_END@.À

ˆ‰SEC117Št�”›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 Hfseek@ and get reliable results for any random access file. However, some ISO 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 Hftell@ 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 Boffset@ argument to Hfseek@ to move back to the same file position.
• In a call to Hfseek@ on a text stream, either the Boffset@ must either be zero; or Bwhence@ must be HSEEK_SET@ and the Boffset@ must be the result of an earlier call to Hftell@ 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 Hungetc@ that haven't been read or discarded. See section ‰ŠP�”›Unreading@�”˜.Àð
But even if you observe these rules, you may still have trouble for long files, because Hftell@ and Hfseek@ use a Hlong 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 Hfgetpos@ and Hfsetpos@ instead. These functions represent the file position using the data type Hfpos_t@, whose internal representation varies from system to system.
These symbols are declared in the header file H`stdio.h'@. ‰IDX567Š

A�”˜Data Type:@ Dfpos_t
Â‰IDX568Š@�”˜This is the type of an object that can encode information about the file position of a stream, for use by the functions Hfgetpos@ and Hfsetpos@.
In the GNU system, Hfpos_t@ is equivalent to Hoff_t@ or Hlong int@. In other systems, it might have a different internal representation.À

AFunction:@ int Dfgetpos@ B(FILE *Bstream@, fpos_t *Bposition@)
Â‰IDX569Š@�”˜This function stores the value of the file position indicator for the stream Bstream@ in the Hfpos_t@ object pointed to by Bposition@. If successful, Hfgetpos@ returns zero; otherwise it returns a nonzero value and stores an implementation-defined positive value in Herrno@.À

AFunction:@ int Dfsetpos@ B(FILE *Bstream@, const fpos_t Bposition@)
Â‰IDX570Š@�”˜This function sets the file position indicator for the stream Bstream@ to the position Bposition@, which must have been set by a previous call to Hfgetpos@ on the same stream. If successful, Hfsetpos@ clears the end-of-file indicator on the stream, discards any characters that were "pushed back" by the use of Hungetc@, and returns a value of zero. Otherwise, Hfsetpos@ returns a nonzero value and stores an implementation-defined positive value in Herrno@.À

ˆ‰SEC118Št�”›Stream Buffering

‰IDX571Š@�”˜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 Bbuffering@.
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 other unexpected behavior.
This section deals only with controlling when characters are transmitted between the stream and the file or device, and Bnot@ 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 section ‰ŠP�”›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 section ‰ŠP�”›Low-Level Input/Output@�”˜.
ˆ‰SEC119ŠT�”›Buffering Concepts

@�”˜There are three different kinds of buffering strategies: þÂ
• Characters written to or read from an Bunbuffered@ stream are transmitted individually to or from the file as soon as possible. ‰IDX572Š
• @�”˜Characters written to a Bline buffered@ stream are transmitted to the file in blocks when a newline character is encountered. ‰IDX573Š
• @�”˜Characters written to or read from a Bfully buffered@ stream are transmitted to or from the file in blocks of arbitrary size. ‰IDX574ŠÀð
@�”˜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 section ‰ŠP�”›Controlling Which Kind of Buffering@�”˜, for information on how to select a different kind of buffering. Usually the automatic selection gives you the most convenient kind of buffering for the file or device you open.
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 Hfflush@, as described in section ‰ŠP�”›Flushing Buffers@�”˜.
ˆ‰SEC120ŠT�”›Flushing Buffers

‰IDX575ŠB�”˜Flushing@ output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically: þÂ
• When you try to do output and the output buffer is full.
• When the stream is closed. See section ‰ŠP�”›Closing Streams@�”˜.
• When the program terminates by calling Hexit@. See section ‰ŠP�”›Normal Termination@�”˜.
• When a newline is written, if the stream is line buffered.
• Whenever an input operation on Bany@ stream actually reads data from its file.Àð
If you want to flush the buffered output at another time, call Hfflush@, which is declared in the header file H`stdio.h'@. ‰IDX576Š

A�”˜Function:@ int Dfflush@ B(FILE *Bstream@)
Â‰IDX577Š@�”˜This function causes any buffered output on Bstream@ to be delivered to the file. If Bstream@ is a null pointer, then Hfflush@ causes buffered output on Ball@ open output streams to be flushed.
This function returns HEOF@ if a write error occurs, or zero otherwise.À

DCompatibility 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.
ˆ‰SEC121ŠT�”›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 Hsetvbuf@ function. ‰IDX578Š
@�”˜The facilities listed in this section are declared in the header file H`stdio.h'@. ‰IDX579Š

A�”˜Function:@ int Dsetvbuf@ B(FILE *Bstream@, char *Bbuf@, int Bmode@, size_t Bsize@)
Â‰IDX580Š@�”˜This function is used to specify that the stream Bstream@ should have the buffering mode Bmode@, which can be either H_IOFBF@ (for full buffering), H_IOLBF@ (for line buffering), or H_IONBF@ (for unbuffered input/output).
If you specify a null pointer as the Bbuf@ argument, then Hsetvbuf@ allocates a buffer itself using Hmalloc@. This buffer will be freed when you close the stream.
Otherwise, Bbuf@ should be a character array that can hold at least Bsize@ 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 Hmalloc@ (see section ‰ŠP�”›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 Hsetvbuf@ function returns zero on success, or a nonzero value if the value of Bmode@ is not valid or if the request could not be honored.À

AMacro:@ int D_IOFBF
Â‰IDX581Š@�”˜The value of this macro is an integer constant expression that can be used as the Bmode@ argument to the Hsetvbuf@ function to specify that the stream should be fully buffered.À

AMacro:@ int D_IOLBF
Â‰IDX582Š@�”˜The value of this macro is an integer constant expression that can be used as the Bmode@ argument to the Hsetvbuf@ function to specify that the stream should be line buffered.À

AMacro:@ int D_IONBF
Â‰IDX583Š@�”˜The value of this macro is an integer constant expression that can be used as the Bmode@ argument to the Hsetvbuf@ function to specify that the stream should be unbuffered.À

AMacro:@ int DBUFSIZ
Â‰IDX584Š@�”˜The value of this macro is an integer constant expression that is good to use for the Bsize@ argument to Hsetvbuf@. This value is guaranteed to be at least H256@.
The value of HBUFSIZ@ is chosen on each system so as to make stream I/O efficient. So it is a good idea to use HBUFSIZ@ as the size for the buffer when you call Hsetvbuf@.
Actually, you can get an even better value to use for the buffer size by means of the Hfstat@ system call: it is found in the Hst_blksize@ field of the file attributes. See section ‰ŠP�”›What the File Attribute Values Mean@�”˜.
Sometimes people also use HBUFSIZ@ as the allocation size of buffers used for related purposes, such as strings used to receive a line of input with Hfgets@ (see section ‰ŠP�”›Character Input@�”˜). There is no particular reason to use HBUFSIZ@ for this instead of any other integer, except that it might lead to doing I/O in chunks of an efficient size.À

AFunction:@ void Dsetbuf@ B(FILE *Bstream@, char *Bbuf@)
Â‰IDX585Š@�”˜If Bbuf@ is a null pointer, the effect of this function is equivalent to calling Hsetvbuf@ with a Bmode@ argument of H_IONBF@. Otherwise, it is equivalent to calling Hsetvbuf@ with Bbuf@, and a Bmode@ of H_IOFBF@ and a Bsize@ argument of HBUFSIZ@.
The Hsetbuf@ function is provided for compatibility with old code; use Hsetvbuf@ in all new programs.À

AFunction:@ void Dsetbuffer@ B(FILE *Bstream@, char *Bbuf@, size_t Bsize@)
Â‰IDX586Š@�”˜If Bbuf@ is a null pointer, this function makes Bstream@ unbuffered. Otherwise, it makes Bstream@ fully buffered using Bbuf@ as the buffer. The Bsize@ argument specifies the length of Bbuf@.
This function is provided for compatibility with old BSD code. Use Hsetvbuf@ instead.À

AFunction:@ void Dsetlinebuf@ B(FILE *Bstream@)
Â‰IDX587Š@�”˜This function makes Bstream@ be line buffered, and allocates the buffer for you.
This function is provided for compatibility with old BSD code. Use Hsetvbuf@ instead.À

ˆ‰SEC122Št�”›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 Hsprintf@ and Hsscanf@ functions. You can also create such a stream explicitly, using the functions described in section ‰ŠP�”›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 section ‰ŠP�”›Programming Your Own Custom Streams@�”˜.
DPortability Note:@ The facilities described in this section are specific to GNU. Other systems or C implementations might or might not provide equivalent functionality.
ˆ‰SEC123ŠT�”›String Streams

‰IDX588Š‰IDX589Š@�”˜The Hfmemopen@ and Hopen_memstream@ functions allow you to do I/O to a string or memory buffer. These facilities are declared in H`stdio.h'@. ‰IDX590Š

A�”˜Function:@ FILE * Dfmemopen@ B(void *Bbuf@, size_t Bsize@, const char *Bopentype@)
Â‰IDX591Š@�”˜This function opens a stream that allows the access specified by the Bopentype@ argument, that reads from or writes to the buffer specified by the argument Bbuf@. This array must be at least Bsize@ bytes long.
If you specify a null pointer as the Bbuf@ argument, Hfmemopen@ dynamically allocates (as with Hmalloc@; see section ‰ŠP�”›Unconstrained Allocation@�”˜) an array Bsize@ bytes long. This is really only useful if you are going to write things to the buffer and then read them back in again, because you have no way of actually getting a pointer to the buffer (for this, try Hopen_memstream@, below). The buffer is freed when the stream is open.
The argument Bopentype@ is the same as in Hfopen@ (See section ‰ŠP�”›Opening Streams@�”˜). If the Bopentype@ 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 Bsize@ argument to account for this. Attempts to write more than Bsize@ 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 Bsize@ bytes. So, if you want to read characters from a null-terminated string, you should supply the length of the string as the Bsize@ argument.À

Here is an example of using Hfmemopen@ to create a stream for reading from a string: #include <stdio.h>

static char buffer[] = "foobar";

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

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

return 0;
}
This program produces the following output: Got f
Got o
Got o
Got b
Got a
Got r

AFunction:@ FILE * Dopen_memstream@ B(char **Bptr@, size_t *Bsizeloc@)
Â‰IDX592Š@�”˜This function opens a stream for writing to a buffer. The buffer is allocated dynamically (as with Hmalloc@; see section ‰ŠP�”›Unconstrained Allocation@�”˜) and grown as necessary.
When the stream is closed with Hfclose@ or flushed with Hfflush@, the locations Bptr@ and Bsizeloc@ are updated to contain the pointer to the buffer and its size. The values thus stored remain valid only as long as no further output on the stream takes place. If you do more output, you must flush the stream again to store new values before you use them again.
A null character is written at the end of the buffer. This null character is Bnot@ included in the size value stored at Bsizeloc@.
You can move the stream's file position with Hfseek@ (see section ‰ŠP�”›File Positioning@�”˜). Moving the file position past the end of the data already written fills the intervening space with zeroes.À

Here is an example of using Hopen_memstream@: #include <stdio.h>

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

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

return 0;
}
This program produces the following output: buf = `hello', size = 5
buf = `hello, world', size = 12
ˆ‰SEC124ŠT�”›Obstack Streams

@�”˜You can open an output stream that puts it data in an obstack. See section ‰ŠP�”›Obstacks@�”˜.

AFunction:@ FILE * Dopen_obstack_stream@ B(struct obstack *Bobstack@)
Â‰IDX593Š@�”˜This function opens a stream for writing data into the obstack Bobstack@. This starts an object in the obstack and makes it grow as data is written (see section ‰ŠP�”›Growing Objects@�”˜).
Calling Hfflush@ on this stream updates the current size of the object to match the amount of data that has been written. After a call to Hfflush@, you can examine the object temporarily.
You can move the file position of an obstack stream with Hfseek@ (see section ‰ŠP�”›File Positioning@�”˜). Moving the file position past the end of the data written fills the intervening space with zeros.
To make the object permanent, update the obstack with Hfflush@, and then use Hobstack_finish@ to finalize the object and get its address. The following write to the stream starts a new object in the obstack, and later writes add to that object until you do another Hfflush@ and Hobstack_finish@.
But how do you find out how long the object is? You can get the length in bytes by calling Hobstack_object_size@ (see section ‰ŠP�”›Status of an Obstack@�”˜), or you can null-terminate the object like this: obstack_1grow (Bobstack@, 0);
Whichever one you do, you must do it Bbefore@ calling Hobstack_finish@. (You can do both if you wish.)À

Here is a sample function that uses Hopen_obstack_stream@: char *
make_message_string (const char *a, int b)
{
FILE *stream = open_obstack_stream (&message_obstack);
output_task (stream);
fprintf (stream, ": ");
fprintf (stream, a, b);
fprintf (stream, "\n");
fclose (stream);
obstack_1grow (&message_obstack, 0);
return obstack_finish (&message_obstack);
}
ˆ‰SEC125ŠT�”›Programming Your Own Custom Streams

‰IDX594Š‰IDX595Š
@�”˜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 Bcustom streams@.
ˆ‰SEC126ŠT�”›Custom Streams and Cookies

‰IDX596Š
@�”˜Inside every custom stream is a special object called the Bcookie@. This is an object supplied by you which records where to fetch or store the data read or written. It is up to you to define a data type to use for the cookie. The stream functions in the library never refer directly to its contents, and they don't even know what the type is; they record its address with type Hvoid *@.
To implement a custom stream, you must specify Bhow@ to fetch or store the data in the specified place. You do this by defining Bhook 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 Hcookie_io_functions_t@.
These facilities are declared in H`stdio.h'@. ‰IDX597Š

A�”˜Data Type:@ Dcookie_io_functions_t
Â‰IDX598Š@�”˜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:
Hcookie_read_function_t *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 HEOF@.
ÂHcookie_write_function_t *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.
ÂHcookie_seek_function_t *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 Hfseek@ on this stream can only seek to locations within the buffer; any attempt to seek outside the buffer will return an HESPIPE@ error.
ÂHcookie_close_function_t *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.Â
À

AFunction:@ FILE * Dfopencookie@ B(void *Bcookie@, const char *Bopentype@, cookie_io_functions_t Bio-functions@)
Â‰IDX599Š@�”˜This function actually creates the stream for communicating with the Bcookie@ using the functions in the Bio-functions@ argument. The Bopentype@ argument is interpreted as for Hfopen@; see section ‰ŠP�”›Opening Streams@�”˜. (But note that the "truncate on open" option is ignored.) The new stream is fully buffered.
The Hfopencookie@ function returns the newly created stream, or a null pointer in case of an error.À

ˆ‰SEC127ŠT�”›Custom Stream Hook Functions

‰IDX600Š
@�”˜Here are more details on how you should define the four hook functions that a custom stream needs.
You should define the function to read data from the cookie as: ssize_t Breader@ (void *Bcookie@, void *Bbuffer@, size_t Bsize@)
This is very similar to the Hread@ function; see section ‰ŠP�”›Input and Output Primitives@�”˜. Your function should transfer up to Bsize@ bytes into the Bbuffer@, and return the number of bytes read, or zero to indicate end-of-file. You can return a value of H-1@ to indicate an error.
You should define the function to write data to the cookie as: ssize_t Bwriter@ (void *Bcookie@, const void *Bbuffer@, size_t Bsize@)
This is very similar to the Hwrite@ function; see section ‰ŠP�”›Input and Output Primitives@�”˜. Your function should transfer up to Bsize@ bytes from the buffer, and return the number of bytes written. You can return a value of H-1@ to indicate an error.
You should define the function to perform seek operations on the cookie as: int Bseeker@ (void *Bcookie@, fpos_t *Bposition@, int Bwhence@)
For this function, the Bposition@ and Bwhence@ arguments are interpreted as for Hfgetpos@; see section ‰ŠP�”›Portable File-Position Functions@�”˜. In the GNU library, Hfpos_t@ is equivalent to Hoff_t@ or Hlong 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 Bposition@. Your function should return a value of H0@ on success and H-1@ to indicate an error.
You should define the function to do cleanup operations on the cookie appropriate for closing the stream as: int Bcleaner@ (void *Bcookie@)
Your function should return H-1@ to indicate an error, and H0@ otherwise.

AData Type:@ Dcookie_read_function
Â‰IDX601Š@�”˜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.À

AData Type:@ Dcookie_write_function
Â‰IDX602Š@�”˜The data type of the write function for a custom stream.À

AData Type:@ Dcookie_seek_function
Â‰IDX603Š@�”˜The data type of the seek function for a custom stream.À

AData Type:@ Dcookie_close_function
Â‰IDX604Š@�”˜The data type of the close function for a custom stream.À

Œ
Go to the ‰ŠP�”›first@�”˜, ‰ŠP�”›previous@�”˜, ‰ŠP�”›next@�”˜, ‰ŠP�”›last@�”˜ section, ‰ŠP�”›table of contents@�”˜.