Go to the previous, next section.

Input/Output on Streams

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

Streams

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

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

Data Type: FILE

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

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

Standard Streams

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

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

Macro: FILE * stdin

The standard input stream, which is the normal source of input for the program.

Macro: FILE * stdout

The standard output stream, which is used for normal output from the program.

Macro: FILE * stderr

The standard error stream, which is used for error messages and diagnostics issued by the program.

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

It is probably not a good idea to close any of the standard streams. But you can use freopen to get te effect of closing one and reopening it. See section Opening Streams.

Opening Streams

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

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

Function: FILE * fopen (const char *filename, const char *opentype)

The fopen function opens a stream for I/O to the file filename, and returns a pointer to the stream.

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

`r'
Open an existing file for reading only.

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

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

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

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

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

As you can see, `+' requests a stream that can do both input and output. When using such a stream, you must call fflush (see section Stream Buffering) or a file positioning function such as fseek (see section File Positioning) when switching from reading to writing or vice versa. Otherwise, internal buffers might not be emptied properly.

The GNU C library defines one additional character for use in opentype: the character `x' insists on creating a new file--if a file filename already exists, fopen fails rather than opening it. This is equivalent to the O_EXCL option to the open function (see section File Status Flags).

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

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

If the open fails, fopen returns a null pointer.

You can have multiple streams (or file descriptors) pointing to the same file open at the same time. If you do only input, this works straightforwardly, but you must be careful if any output streams are included. See section Precautions for 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 File Locks.

Macro: int FOPEN_MAX

The value of this macro is an integer constant expression that represents the minimum number of streams that the implementation guarantees can be open simultaneously. The value of this constant is at least eight, which includes the three standard streams stdin, stdout, and stderr.

Function: FILE * freopen (const char *filename, const char *opentype, FILE *stream)

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

If the operation fails, a null pointer is returned; otherwise, freopen returns stream.

The main use of freopen is to connect a standard stream such as stdir with a file of your own choice. This is useful in programs in which use of a standard stream for certain purposes is hard-coded.

Closing Streams

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

Function: int fclose (FILE *stream)

This function causes stream to be closed and the connection to the corresponding file to be broken. Any buffered output is written and any buffered input is discarded. The fclose function returns a value of 0 if the file was closed successfully, and EOF if an error was detected.

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

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

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

Simple Output by Characters or Lines

This section describes functions for performing character- and line-oriented output. Largely for historical compatibility, there are several variants of these functions, but as a matter of style (and for simplicity!) we suggest you stick with using fputc and fputs, and perhaps putc and putchar.

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

Function: int fputc (int c, FILE *stream)

The fputc function converts the character c to type unsigned char, and writes it to the stream stream. EOF is returned if a write error occurs; otherwise the character c is returned.

Function: int putc (int c, FILE *stream)

This is just like fputc, except that most systems implement it as a macro, making it faster. One consequence is that it may evaluate the stream argument more than once.

Function: int putchar (int c)

The putchar function is equivalent to fputc with stdout as the value of the stream argument.

Function: int fputs (const char *s, FILE *stream)

The function fputs writes the string s to the stream stream. The terminating null character is not written. This function does not add a newline character, either. It outputs only the chars in the string.

This function returns EOF if a write error occurs, and otherwise a non-negative value.

For example:

fputs ("Are ", stdout);
fputs ("you ", stdout);
fputs ("hungry?\n", stdout);

outputs the text `Are you hungry?' followed by a newline.

Function: int puts (const char *s)

The puts function writes the string s to the stream stdout followed by a newline. The terminating null character of the string is not written.

Function: int putw (int w, FILE *stream)

This function writes the word w (that is, an int) to stream. It is provided for compatibility with SVID, but we recommend you use fwrite instead (see section Block Input/Output).

Character Input

This section describes functions for performing character- and line-oriented input. Again, there are several variants of these functions, some of which are considered obsolete stylistically. It's suggested that you stick with fgetc, getline, and maybe getc, getchar and fgets.

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

Function: int fgetc (FILE *stream)

This function reads the next character as an unsigned char from the stream stream and returns its value, converted to an int. If an end-of-file condition or read error occurs, EOF is returned instead.

Function: int getc (FILE *stream)

This is just like fgetc, except that it is permissible (and typical) for it to be implemented as a macro that evaluates the stream argument more than once.

Function: int getchar (void)

The getchar function is equivalent to fgetc with stdin as the value of the stream argument.

Here is an example of a function that does input using fgetc. It would work just as well using getc instead, or using getchar () instead of fgetc (stdin).

int
y_or_n_p (const char *question)
{
  fputs (question, stdout);
  while (1) {
    int c, answer;
    /* Write a space to separate answer from question. */
    fputc (' ', stdout);
    /* Read the first character of the line.
       This should be the answer character, but might not be. */
    c = tolower (fgetc (stdin));
    answer = c;
    /* Discard rest of input line. */
    while (c != '\n')
      c = fgetc (stdin);
    /* Obey the answer if it was valid. */
    if (answer == 'y')
      return 1;
    if (answer == 'n')
      return 0;
    /* Answer was invalid: ask for valid answer. */
    fputs ("Please answer y or n:", stdout);
  }
}

Function: int getw (FILE *stream)

This function reads a word (that is, an int) from stream. It's provided for compatibility with SVID. We recommend you use fread instead (see section Block Input/Output).

Line-Oriented Input

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

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

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

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

Function: ssize_t getline (char **lineptr, size_t *n, FILE *stream)

This function reads an entire line from stream, storing the text (including the newline and a terminating null character) in a buffer and storing the buffer address in *lineptr.

Before calling getline, you should place in *lineptr the address of a buffer *n bytes long. If this buffer is long enough to hold the line, getline stores the line in this buffer. Otherwise, getline makes the buffer bigger using realloc, storing the new buffer address back in *lineptr and the increased size back in *n.

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

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

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

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

Function: ssize_t getdelim (char **lineptr, size_t *n, int delimiter, FILE *stream)

This function is like getline except that the character which tells it to stop reading is not necessarily newline. The argument delimeter specifies the delimeter character; getdelim keeps reading until it sees that character (or end of file).

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

Function: char * fgets (char *s, int count, FILE *stream)

The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string. You must supply count characters worth of space in s, but the number of characters read is at most count - 1. The extra character space is used to hold the null character at the end of the string.

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

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

Deprecated function: char * gets (char *s)

The function gets reads characters from the stream stdin up to the next newline character, and stores them in the string s. The newline character is discarded (note that this differs from the behavior of fgets, which copies the newline character into the string).

Warning: The gets function is very dangerous because it provides no protection against overflowing the string s. The GNU library includes it for compatibility only. You should always use fgets or getline instead.

Unreading

In parser programs it is often useful to examine the next character in the input stream without removing it from the stream. This is called "peeking ahead" at the input because your program gets a glimpse of the input it will read next.

Using stream I/O, you can peek ahead at input by first reading it and then unreading it (also called pushing it back on the stream). Unreading a character makes it available to be input again from the stream, by the next call to fgetc or other input function on that stream.

What Unreading Means

Here is a pictorial explanation of unreading. Suppose you have a stream reading a file that contains just six characters, the letters `foobar'. Suppose you have read three characters so far. The situation looks like this:

f  o  o  b  a  r
         ^

so the next input character will be `b'.

If instead of reading `b' you unread the letter `o', you get a situation like this:

f  o  o  b  a  r
         |
      o--
      ^

so that the next input characters will be `o' and `b'.

If you unread `9' instead of `o', you get this situation:

f  o  o  b  a  r
         |
      9--
      ^

so that the next input characters will be `9' and `b'.

Using ungetc To Do Unreading

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

Function: int ungetc (int c, FILE *stream)

The ungetc function pushes back the character c onto the input stream stream. So the next input from stream will read c before anything else.

The character that you push back doesn't have to be the same as the last character that was actually read from the stream. In fact, it isn't necessary to actually read any characters from the stream before unreading them with ungetc! But that is a strange way to write a program; usually ungetc is used only to unread a character that was just read from the same stream.

The GNU C library only supports one character of pushback--in other words, it does not work to call ungetc twice without doing input in between. Other systems might let you push back multiple characters; then reading from the stream retrieves the characters in the reverse order that they were pushed.

Pushing back characters doesn't alter the file; only the internal buffering for the stream is affected. If a file positioning function (such as fseek or rewind; see section File Positioning) is called, any pending pushed-back characters are discarded.

Unreading a character on a stream that is at end of file clears the end-of-file indicator for the stream, because it makes the character of input available. Reading that character will set the end-of-file indicator again.

Here is an example showing the use of getc and ungetc to skip over whitespace characters. When this function reaches a non-whitespace character, it unreads that character to be seen again on the next read operation on the stream.

#include <stdio.h>

void
skip_whitespace (FILE *stream)
{
  int c;
  do
    /* No need to check for EOF because it is not
       isspace, and ungetc ignores EOF.  */
    c = getc (stream);
  while (isspace (c));
  ungetc (c, stream);
}

Formatted Output

The functions described in this section (printf and related functions) provide a convenient way to perform formatted output. You call printf with a format string or template string that specifies how to format the values of the remaining arguments.

Unless your program is a filter that specifically performs line- or character-oriented processing, using printf or one of the other related functions described in this section is usually the easiest and most concise way to perform output. These functions are especially useful for printing error messages, tables of data, and the like.

Formatted Output Basics

The printf function can be used to print any number of arguments. The template string argument you supply in a call provides information not only about the number of additional arguments, but also about their types and what style should be used for printing them.

Ordinary characters in the template string are simply written to the output stream as-is, while conversion specifications introduced by a `%' character in the template cause subsequent arguments to be formatted and written to the output stream. For example,

int pct = 37;
char filename[] = "foo.txt";
printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
        filename, pct);

produces output like

Processing of `foo.txt' is 37% finished.
Please be patient.

This example shows the use of the `%d' conversion to specify that an int argument should be printed in decimal notation, the `%s' conversion to specify printing of a string argument, and the `%%' conversion to print a literal `%' character.

There are also conversions for printing an integer argument as an unsigned value in octal, decimal, or hexadecimal radix (`%o', `%u', or `%x', respectively); or as a character value (`%c').

Floating-point numbers can be printed in normal, fixed-point notation using the `%f' conversion or in exponential notation using the `%e' conversion. The `%g' conversion uses either `%e' or `%f' format, depending on what is more appropriate for the magnitude of the particular number.

You can control formatting more precisely by writing modifiers between the `%' 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.

Output Conversion Syntax

This section provides details about the precise syntax of conversion specifications that can appear in a printf template string.

Characters in the template string that are not part of a conversion specification are printed as-is to the output stream. Multibyte character sequences (see section Extended Characters) are permitted in a template string.

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

% flags width [ . precision ] type conversion

For example, in the conversion specifier `%-10.8ld', the `-' is a flag, `10' specifies the field width, the precision is `8', the letter `l' is a type modifier, and `d' specifies the conversion style. (This particular type specifier says to print a long int argument in decimal notation, with a minimum of 8 digits left-justified in a field at least 10 characters wide.)

In more detail, output conversion specifications consist of an initial `%' character followed in sequence by:

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

Table of Output Conversions

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

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

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

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

`%Z'
Print an integer as an unsigned decimal number, assuming it was passed with type size_t. See section Integer Conversions, for details.

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

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

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

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

`%c'
Print a single character. See section Other Output Conversions.

`%s'
Print a string. See section Other Output Conversions.

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

`%n'
Get the number of characters printed so far. See section Other Output Conversions. Note that this conversion specification never produces any output.

`%m'
Print the string corresponding to the value of errno. See section Other Output Conversions.

`%%'
Print a literal `%' character. See section 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.

Integer Conversions

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

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

The following flags are meaningful:

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

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

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

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

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

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

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

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

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

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

The modifiers for argument type are not applicable to `%Z', since the sole purpose of `%Z' is to specify the data type size_t.

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 `%d' conversion gives results like:

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

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

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

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

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

Floating-Point Conversions

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

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

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

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

The following flags can be used to modify the behavior:

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

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

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

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

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

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

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

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

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

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

Here is the output:

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

Notice how the `%g' conversion drops trailing zeros.

Other Output Conversions

This section describes miscellaneous conversions for printf.

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

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

prints `hello'.

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

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

prints ` nowhere '.

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

The `%m' conversion prints the string corresponding to the error code in errno. See section 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 `%m' conversion is a GNU C library extension.

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

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

For example:

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

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

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

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

For example,

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

prints:

3 bears

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

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

Formatted Output Functions

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

Function: int printf (const char *template, ...)

The printf function prints the optional arguments under the control of the template string template to the stream stdout. It returns the number of characters printed, or a negative value if there was an output error.

Function: int fprintf (FILE *stream, const char *template, ...)

This function is just like printf, except that the output is written to the stream stream instead of stdout.

Function: int sprintf (char *s, const char *template, ...)

This is like printf, except that the output is stored in the character array s instead of written to a stream. A null character is written to mark the end of the string.

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

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

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

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

Function: int snprintf (char *s, size_t size, const char *template, ...)

The snprintf function is similar to sprintf, except that the size argument specifies the maximum number of characters to produce. The trailing null character is counted towards this limit, so you should allocate at least size characters for the string s.

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

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

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

Dynamically Allocating Formatted Output

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

Function: int asprintf (char **ptr, const char *template, ...)

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

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

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

Function: int obstack_printf (struct obstack *obstack, const char *template, ...)

This function is similar to asprintf, except that it uses the obstack obstack to allocate the space. See section Obstacks.

The characters are written onto the end of the current object. To get at them, you must finish the object with obstack_finish (see section Growing Objects).

Variable Arguments Output Functions

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

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

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

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

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

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

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

Prototypes for these functions are declared in `stdio.h'.

Function: int vprintf (const char *template, va_list ap)

This function is similar to printf except that, instead of taking a variable number of arguments directly, it takes an argument list pointer ap.

Function: int vfprintf (FILE *stream, const char *template, va_list ap)

This is the equivalent of fprintf with the variable argument list specified directly as for vprintf.

Function: int vsprintf (char *s, const char *template, va_list ap)

This is the equivalent of sprintf with the variable argument list specified directly as for vprintf.

Function: int vsnprintf (char *s, size_t size, const char *template, va_list ap)

This is the equivalent of snprintf with the variable argument list specified directly as for vprintf.

Function: int vasprintf (char **ptr, const char *template, va_list ap)

The vasprintf function is the equivalent of asprintf with the variable argument list specified directly as for vprintf.

Function: int obstack_vprintf (struct obstack *obstack, const char *template, va_list ap)

The obstack_vprintf function is the equivalent of obstack_printf with the variable argument list specified directly as for vprintf.

Here's an example showing how you might use vfprintf. This is a function that prints error messages to the stream stderr, along with a prefix indicating the name of the program (see section Error Messages, for a description of program_invocation_short_name).

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

void
eprintf (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 eprintf like this:

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

Parsing a Template String

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

All the symbols described in this section are declared in the header file `printf.h'.

Function: size_t parse_printf_format (const char *template, size_t n, int *argtypes)

This function returns information about the number and types of arguments expected by the printf template string template. The information is stored in the array argtypes; each element of this array describes one argument. This information is encoded using the various `PA_' macros, listed below.

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

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

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

Macro: int PA_FLAG_MASK

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

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

PA_INT
This specifies that the base type is int.

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

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

PA_POINTER
This specifies that the base type is void *, an arbitrary pointer.

PA_FLOAT
This specifies that the base type is float.

PA_DOUBLE
This specifies that the base type is double.

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

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

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

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

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

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

PA_FLAG_LONG_LONG
If this bit is set, it indicates that the base type is modified with long long. (This corresponds to the `L' type modifier.)

PA_FLAG_LONG_DOUBLE
This is a synonym for PA_FLAG_LONG_LONG, used by convention with a base type of PA_DOUBLE to indicate a type of long double.

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 NUMBER, CHAR, STRING and STRUCTURE (and perhaps others which are not valid here).

/* Test whether the nargs specified objects
   in the vector args are valid
   for the format string format:
   if so, return 1.
   If not, return 0 after printing an error message.  */

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

  /* Get the information about the arguments.  */
  while (1) {
    argtypes = (int *) alloca (nelts * sizeof (int));
    nwanted = parse_printf_format (string, nelts, argtypes);
    if (nwanted <= nelts)
      break;
    nelts *= 2;
  }

  /* 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;
}

Customizing printf

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

The way you do this is by registering the conversion with register_printf_function; see section 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 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 Parsing a Template String, for information about this.

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

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

Registering New Conversions

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

Function: int register_printf_function (int spec, printf_function handler_function, printf_arginfo_function arginfo_function)

This function defines the conversion specifier character spec. Thus, if spec is 'q', it defines the conversion `%q'.

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

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

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

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

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

Conversion Specifier Options

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

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

Type: struct printf_info

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

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

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

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

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

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

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

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

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

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

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

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

Defining the Output Handler

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

You should define your handler functions with a prototype like:

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

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

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

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

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

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

Data Type: printf_function

This is the data type that a handler function should have.

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

You should define these functions with a prototype like:

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

The return value from the function should be the number of arguments the conversion expects, up to a maximum of n. The function should also fill in the argtypes array with information about the types of each of these arguments. This information is encoded using the various `PA_' macros. (You will notice that this is the same calling convention parse_printf_format itself uses.)

Data Type: printf_arginfo_function

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

printf Extension Example

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

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

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
main (void)
{
  /* Make a widget to print.  */
  Widget mywidget;
  mywidget.name = "mywidget";

  /* Register the print function for widgets.  */
  register_printf_function ('W', print_widget, NULL); /* No 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>      |

Formatted Input

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

Formatted Input Basics

Calls to scanf are superficially similar to calls to printf in that arbitrary arguments are read under the control of a template string. While the syntax of the conversion specifications in the template is very similar to that for printf, the interpretation of the template is oriented more towards free-format input and simple pattern matching, rather than fixed-field formatting. For example, most scanf conversions skip over any amount of "white space" (including spaces, tabs, 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.

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

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

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

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 Bison to generate a parser, rather than using scanf. For more information about this, see section 'Bison' in The Bison Reference Manual.

Input Conversion Syntax

A scanf template string is a string that contains ordinary multibyte characters interspersed with conversion specifications that start with `%'.

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

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

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

% flags width type conversion

In more detail, an input conversion specification consists of an initial `%' character followed in sequence by:

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.

Table of Input Conversions

Here is a table that summarizes the various conversion specifications:

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

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

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

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

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

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

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

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

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

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

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

`%%'
This matches a literal `%' character in the input stream. No corresponding argument is used. See section 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.

Numeric Input Conversions

This section describes the scanf conversions for reading numeric values.

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

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

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

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

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

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

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

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

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

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

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

`l'
Specifies that the argument is of type double *.

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

String Input Conversions

This section describes the scanf input conversions for reading string and character values: `%s', `%[', and `%c'.

You have two options for how to receive the input from these conversions:

The `%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 n characters, and fails if it cannot get that many. Since there is always a maximum field width with `%c' (whether specified, or 1 by default), you can always prevent overflow by making the buffer long enough.

The `%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 `%10c' produces " hello, wo", but reading the same input with the conversion `%10s' produces "hello,".

Warning: If you do not specify a field width for `%s', then the number of characters read is limited only by where the next whitespace character appears. This almost certainly means 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 `%[' conversion. You specify the set between the `[' character and a following `]' character, using the same syntax used in regular expressions. As special cases:

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

Here are some examples of `%[' conversions and what they mean:

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

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

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

`%25[a-z]'
Matches up to 25 lowercase characters.

One more reminder: the `%s' and `%[' conversions are dangerous if you don't specify a maximum width or use the `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.

Dynamically Allocating String Conversions

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

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

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

{
  char *variable, *value;

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

  ...
}

Other Input Conversions

This section describes the miscellaneous input conversions.

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

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

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

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

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

Formatted Input Functions

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

Function: int scanf (const char *template, ...)

The scanf function reads formatted input from the stream stdin under the control of the template string template. The optional arguments are pointers to the places which receive the resulting values.

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

Function: int fscanf (FILE *stream, const char *template, ...)

This function is just like scanf, except that the input is read from the stream stream instead of stdin.

Function: int sscanf (const char *s, const char *template, ...)

This is like scanf, except that the characters are taken from the null-terminated string s instead of from a stream. Reaching the end of the string is treated as an end-of-file condition.

The behavior of this function is undefined if copying takes place between objects that overlap--for example, if s is also given as an argument to receive a string read under control of the `%s' conversion.

Variable Arguments Input Functions

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

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

Function: int vscanf (const char *template, va_list ap)

This function is similar to scanf except that, instead of taking a variable number of arguments directly, it takes an argument list pointer ap of type va_list (see section Variadic Functions).

Function: int vfscanf (FILE *stream, const char *template, va_list ap)

This is the equivalent of fscanf with the variable argument list specified directly as for vscanf.

Function: int vsscanf (const char *s, const char *template, va_list ap)

This is the equivalent of sscanf with the variable argument list specified directly as for vscanf.

Block Input/Output

This section describes how to do input and output operations on blocks of data. You can use these functions to read and write binary data, as well as to read and write text in fixed-size blocks instead of by characters or lines.

Binary files are typically used to read and write blocks of data in the same format as is used to represent the data in a running program. In other words, arbitrary blocks of memory--not just character or string objects--can be written to a binary file, and meaningfully read in again by the same program.

Storing data in binary form is often considerably more efficient than using the formatted I/O functions. Also, for floating-point numbers, the binary form avoids possible loss of precision in the conversion process. On the other hand, binary files can't be examined or modified easily using many standard file utilities (such as text editors), and are not portable between different implementations of the language, or different kinds of computers.

These functions are declared in `stdio.h'.

Function: size_t fread (void *data, size_t size, size_t count, FILE *stream)

This function reads up to count objects of size size into the array data, from the stream stream. It returns the number of objects actually read, which might be less than count if a read error occurs or the end of the file is reached. This function returns a value of zero (and doesn't read anything) if either size or count is zero.

If fread encounters end of file in the middle of an object, it returns the number of complete objects read, and discards the partial object. Therefore, the stream remains at the actual end of the file.

Function: size_t fwrite (const void *data, size_t size, size_t count, FILE *stream)

This function writes up to count objects of size size from the array data, to the stream stream. The return value is normally count, if the call succeeds. Any other value indicates some sort of error, such as running out of space.

End-Of-File and Errors

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

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

Macro: int EOF

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

Function: void clearerr (FILE *stream)

This function clears the end-of-file and error indicators for the stream stream.

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

Function: int feof (FILE *stream)

The feof function returns nonzero if and only if the end-of-file indicator for the stream stream is set.

Function: int ferror (FILE *stream)

The ferror function returns nonzero if and only if the error indicator for the stream stream is set, indicating that an error has occurred on a previous operation on the stream.

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

Text and Binary Streams

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

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

Text and binary streams differ in several ways:

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

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

File Positioning

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

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

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

Function: long int ftell (FILE *stream)

This function returns the current file position of the stream stream.

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

Function: int fseek (FILE *stream, long int offset, int whence)

The fseek function is used to change the file position of the stream stream. The value of whence must be one of the constants SEEK_SET, SEEK_CUR, or SEEK_END, to indicate whether the offset is relative to the beginning of the file, the current file position, or the end of the file, respectively.

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

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

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

The following symbolic constants are defined for use as the whence argument to fseek. They are also used with the lseek function (see section Input and Output Primitives) and to specify offsets for file locks (see section Control Operations on Files).

Macro: int SEEK_SET

This is an integer constant which, when used as the whence argument to the fseek function, specifies that the offset provided is relative to the beginning of the file.

Macro: int SEEK_CUR

This is an integer constant which, when used as the whence argument to the fseek function, specifies that the offset provided is relative to the current file position.

Macro: int SEEK_END

This is an integer constant which, when used as the whence argument to the fseek function, specifies that the offset provided is relative to the end of the file.

Function: void rewind (FILE *stream)

The rewind function positions the stream stream at the begining of the file. It is equivalent to calling fseek on the stream with an offset argument of 0L and a whence argument of SEEK_SET, except that the return value is discarded and the error indicator for the stream is reset.

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

L_SET
An alias for SEEK_SET.

L_INCR
An alias for SEEK_CUR.

L_XTND
An alias for SEEK_END.

Portable File-Position Functions

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

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

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

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

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

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

Data Type: fpos_t

This is the type of an object that can encode information about the file position of a stream, for use by the functions fgetpos and fsetpos.

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

Function: int fgetpos (FILE *stream, fpos_t *position)

This function stores the value of the file position indicator for the stream stream in the fpos_t object pointed to by position. If successful, fgetpos returns zero; otherwise it returns a nonzero value and stores an implementation-defined positive value in errno.

Function: int fsetpos (FILE *stream, const fpos_t position)

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

Stream Buffering

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

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

This section deals only with controlling when characters are transmitted between the stream and the file or device, and not with how things like echoing, flow control, and the like are handled on specific classes of devices. For information on common control operations on terminal devices, see section 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 Low-Level Input/Output.

Buffering Concepts

There are three different kinds of buffering strategies:

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 Controlling Which Kind of Buffering, for information on how to select a different kind of buffering.

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

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

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

Flushing Buffers

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

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

Function: int fflush (FILE *stream)

This function causes any buffered output on stream to be delivered to the file. If stream is a null pointer, then fflush causes buffered output on all open output streams to be flushed.

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

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

Controlling Which Kind of Buffering

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

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

Function: int setvbuf (FILE *stream, char *buf, int mode, size_t size)

This function is used to specify that the stream stream should have the buffering mode mode, which can be either _IOFBF (for full buffering), _IOLBF (for line buffering), or _IONBF (for unbuffered input/output).

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

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

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

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

Macro: int _IOFBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be fully buffered.

Macro: int _IOLBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be line buffered.

Macro: int _IONBF

The value of this macro is an integer constant expression that can be used as the mode argument to the setvbuf function to specify that the stream should be unbuffered.

Macro: int BUFSIZ

The value of this macro is an integer constant expression that is good to use for the size argument to setvbuf. This value is guaranteed to be at least 256.

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

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

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

Function: void setbuf (FILE *stream, char *buf)

If buf is a null pointer, the effect of this function is equivalent to calling setvbuf with a mode argument of _IONBF. Otherwise, it is equivalent to calling setvbuf with buf, and a mode of _IOFBF and a size argument of BUFSIZ.

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

Function: void setbuffer (FILE *stream, char *buf, size_t size)

If buf is a null pointer, this function makes stream unbuffered. Otherwise, it makes stream fully buffered using buf as the buffer. The size argument specifies the length of buf.

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

Function: void setlinebuf (FILE *stream)

This function makes stream be line buffered, and allocates the buffer for you.

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

Temporary Files

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

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

Function: FILE * tmpfile (void)

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

Function: char * tmpnam (char *result)

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

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

Macro: int L_tmpnam

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

Macro: int TMP_MAX

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

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

Function: char * tempnam (const char *dir, const char *prefix)

This function generates a unique temporary filename. If prefix is not a null pointer, up to five characters of this string are used as a prefix for the file name.

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

This function is defined for SVID compatibility.

SVID Macro: char * P_tmpdir

This macro is the name of the default directory for temporary files.

Other Kinds of Streams

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

One such type of stream takes input from or writes output to a string. These kinds of streams are used internally to implement the sprintf and sscanf functions. You can also create such a stream explicitly, using the functions described in section 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 Programming Your Own Custom Streams.

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

String Streams

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

Function: FILE * fmemopen (void *buf, size_t size, const char *opentype)

This function opens a stream that allows the access specified by the opentype argument, that reads from or writes to the buffer specified by the argument buf. This array must be at least size bytes long.

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

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

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

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

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

#include <stdio.h>

static char buffer[] = "foobar";

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

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

  return 0;
}

This program produces the following output:

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

Function: FILE * open_memstream (char **ptr, size_t *sizeloc)

This function opens a stream for writing to a buffer. The buffer is allocated dynamically (as with malloc; see section Unconstrained Allocation) and grown as necessary.

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

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

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

Here is an example of using open_memstream:

#include <stdio.h>

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

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

  return 0;
}

This program produces the following output:

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

Obstack Streams

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

Function: FILE * open_obstack_stream (struct obstack *obstack)

This function opens a stream for writing data into the obstack obstack. This starts an object in the obstack and makes it grow as data is written (see section Growing Objects).

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

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

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

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

obstack_1grow (obstack, 0);

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

Here is a sample function that uses open_obstack_stream:

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

Programming Your Own Custom Streams

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

Custom Streams and Cookies

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

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

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

These facilities are declared in `stdio.h'.

Data Type: struct cookie_io_functions

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

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

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

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

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

Function: FILE * fopencookie (void *cookie, const char *opentype, struct cookie_functions io_functions)

This function actually creates the stream for communicating with the cookie using the functions in the io_functions argument. The opentype argument is interpreted as for fopen; see section Opening Streams. (But note that the "truncate on open" option is ignored.) The new stream is fully buffered.

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

Custom Stream Hook Functions

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

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

ssize_t reader (void *cookie, void *buffer, size_t size)

This is very similar to the read function; see section Input and Output Primitives. Your function should transfer up to size bytes into the buffer, and return the number of bytes read, or zero to indicate end-of-file. You can return a value of -1 to indicate an error.

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

ssize_t writer (void *cookie, const void *buffer, size_t size)

This is very similar to the write function; see section Input and Output Primitives. Your function should transfer up to size bytes from the buffer, and return the number of bytes written. You can return a value of -1 to indicate an error.

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

int seeker (void *cookie, fpos_t *position, int whence)

For this function, the position and whence arguments are interpreted as for fgetpos; see section Portable File-Position Functions. In the GNU library, fpos_t is equivalent to off_t or long int, and simply represents the number of bytes from the beginning of the file.

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

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

int cleaner (void *cookie)

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

Data Type: cookie_read_function

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

Data Type: cookie_write_function

The data type of the write function for a custom stream.

Data Type: cookie_seek_function

The data type of the seek function for a custom stream.

Data Type: cookie_close_function

The data type of the close function for a custom stream.

Go to the previous, next section.