This chapter describes the functions for creating streams and performing input and output operations on them. As discussed in section 6 Input/Output Overview, a stream is a fairly abstract, high-level concept representing a communications channel to a file, device, or process.
printf
and related functions.
printf
and friends.
scanf
and related functions.
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'.
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 7.13 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.
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'.
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 9 File System Interface.) Most other operating systems provide similar mechanisms, but the details of how to use them can vary.
In the GNU C library, stdin
, stdout
, and stderr
are
normal variables which you can set just like any others. For example, to redirect
the standard output to a file, you could do:
fclose (stdout); stdout = fopen ("standard-output-file", "w");
Note however, that in other systems stdin
, stdout
, and
stderr
are macros that you cannot assign to in the normal way.
But you can use freopen
to get the effect of closing one and
reopening it. See section 7.3 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'.
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:
As you can see, `+' requests a stream that can do both input and
output. The ISO standard says that when using such a stream, you must
call fflush
(see section 7.17 Stream Buffering) or a file positioning
function such as fseek
(see section 7.15 File Positioning) when switching
from reading to writing or vice versa. Otherwise, internal buffers
might not be emptied properly. The GNU C library does not have this
limitation; you can do arbitrary reading and writing operations on a
stream in whatever order.
Additional characters may appear after these to specify flags for the call. Always put the mode (`r', `w+', etc.) first; that is the only part you are guaranteed will be understood by all systems.
The GNU C library defines one additional character for use in
opentype: the character `x' insists on creating a new
file--if a file filename already exists, fopen
fails
rather than opening it. If you use `x' you can are guaranteed that
you will not clobber an existing file. This is equivalent to the
O_EXCL
option to the open
function (see section 8.1 Opening and Closing Files).
The character `b' in opentype has a standard meaning; it requests a binary stream rather than a text stream. But this makes no difference in POSIX systems (including the GNU system). If both `+' and `b' are specified, they can appear in either order. See section 7.14 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 8.5 Dangers of Mixing Streams and Descriptors. This is equally true whether the streams are in one program (not usual) or in several programs (which can easily happen). It may be advantageous to use the file locking facilities to avoid simultaneous access. See section 8.11 File Locks.
stdin
, stdout
, and stderr
. In POSIX.1 systems this
value is determined by the OPEN_MAX
parameter; see section 28.1 General Capacity Limits. In BSD and GNU, it is controlled by the RLIMIT_NOFILE
resource limit; see section 17.6 Limiting Resource Usage.
fclose
and fopen
.
It first closes the stream referred to by stream, ignoring any
errors that are detected in the process. (Because errors are ignored,
you should not use freopen
on an output stream if you have
actually done any output using the stream.) Then the file named by
filename is opened with mode opentype as for fopen
,
and associated with the same stream object stream.
If the operation fails, a null pointer is returned; otherwise,
freopen
returns stream.
freopen
has traditionally been used to connect a standard stream
such as stdin
with a file of your own choice. This is useful in
programs in which use of a standard stream for certain purposes is
hard-coded. In the GNU C library, you can simply close the standard
streams and open new ones with fopen
. But other systems lack
this ability, so using freopen
is more portable.
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.
fclose
function returns
a value of 0
if the file was closed successfully, and EOF
if an error was detected.
It is important to check for errors when you call fclose
to close
an output stream, because real, everyday errors can be detected at this
time. For example, when fclose
writes the remaining buffered
output, it might get an error because the disk is full. Even if you
know the buffer is empty, errors can still occur when closing a file if
you are using NFS.
The function fclose
is declared in `stdio.h'.
To close all streams currently available the GNU C Library provides another function.
fcloseall
function returns a value of 0
if all the files were closed
successfully, and EOF
if an error was detected.
This function should be used in only in special situation, e.g., when an error occurred and the program must be aborted. Normally each single stream should be closed separately so that problems with one stream can be identifier. It is also problematic since the standard streams (see section 7.2 Standard Streams) will also be closed.
The function fcloseall
is declared in `stdio.h'.
If the main
function to your program returns, or if you call the
exit
function (see section 22.3.1 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 22.3.4 Aborting a Program) or from a fatal signal (see section 21 Signal Handling), open streams
might not be closed properly. Buffered output might not be flushed and
files may be incomplete. For more information on buffering of streams,
see section 7.17 Stream Buffering.
This section describes functions for performing character- and line-oriented output.
These functions are declared in the header file `stdio.h'.
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.
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, which is an exception to the
general rule for macros. putc
is usually the best function to
use for writing a single character.
putchar
function is equivalent to putc
with
stdout
as the value of the stream argument.
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 characters 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.
puts
function writes the string s to the stream
stdout
followed by a newline. The terminating null character of
the string is not written. (Note that fputs
does not
write a newline as this function does.)
puts
is the most convenient function for printing simple
messages. For example:
puts ("This is a message.");
int
) to
stream. It is provided for compatibility with SVID, but we
recommend you use fwrite
instead (see section 7.9 Block Input/Output).
This section describes functions for performing character-oriented input. These functions are declared in the header file `stdio.h'.
These functions return an int
value that is either a character of
input, or the special value EOF
(usually -1). It is important to
store the result of these functions in a variable of type int
instead of char
, even when you plan to use it only as a
character. Storing EOF
in a char
variable truncates its
value to the size of a character, so that it is no longer
distinguishable from the valid character `(char) -1'. So always
use an int
for the result of getc
and friends, and check
for EOF
after the call; once you've verified that the result is
not EOF
, you can be sure that it will fit in a `char'
variable without loss of information.
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.
fgetc
, except that it is permissible (and
typical) for it to be implemented as a macro that evaluates the
stream argument more than once. getc
is often highly
optimized, so it is usually the best function to use to read a single
character.
getchar
function is equivalent to getc
with stdin
as the value of the stream argument.
Here is an example of a function that does input using fgetc
. It
would work just as well using getc
instead, or using
getchar ()
instead of fgetc (stdin)
.
int y_or_n_p (const char *question) { fputs (question, stdout); while (1) { int c, answer; /* Write a space to separate answer from question. */ fputc (' ', stdout); /* Read the first character of the line. This should be the answer character, but might not be. */ c = tolower (fgetc (stdin)); answer = c; /* Discard rest of input line. */ while (c != '\n' && c != EOF) c = fgetc (stdin); /* Obey the answer if it was valid. */ if (answer == 'y') return 1; if (answer == 'n') return 0; /* Answer was invalid: ask for valid answer. */ fputs ("Please answer y or n:", stdout); } }
int
) from stream.
It's provided for compatibility with SVID. We recommend you use
fread
instead (see section 7.9 Block Input/Output). Unlike getc
,
any int
value could be a valid result. getw
returns
EOF
when it encounters end-of-file or an error, but there is no
way to distinguish this from an input word with value -1.
Since many programs interpret input on the basis of lines, it's convenient to have functions to read a line of text from a stream.
Standard C has functions to do this, but they aren't very safe: null
characters and even (for gets
) long lines can confuse them. So
the GNU library provides the nonstandard getline
function that
makes it easy to read lines reliably.
Another GNU extension, getdelim
, generalizes getline
. It
reads a delimited record, defined as everything through the next
occurrence of a specified delimiter character.
All these functions are declared in `stdio.h'.
*lineptr
.
Before calling getline
, you should place in *lineptr
the address of a buffer *n
bytes long, allocated with
malloc
. If this buffer is long enough to hold the line,
getline
stores the line in this buffer. Otherwise,
getline
makes the buffer bigger using realloc
, storing the
new buffer address back in *lineptr
and the increased size
back in *n
.
See section 3.3 Unconstrained Allocation.
If you set *lineptr
to a null pointer, and *n
to zero, before the call, then getline
allocates the initial
buffer for you by calling malloc
.
In either case, when getline
returns, *lineptr
is
a char *
which points to the text of the line.
When getline
is successful, it returns the number of characters
read (including the newline, but not including the terminating null).
This value enables you to distinguish null characters that are part of
the line from the null character inserted as a terminator.
This function is a GNU extension, but it is the recommended way to read lines from a stream. The alternative standard functions are unreliable.
If an error occurs or end of file is reached, getline
returns
-1
.
getline
except that the character which
tells it to stop reading is not necessarily newline. The argument
delimiter specifies the delimiter character; getdelim
keeps
reading until it sees that character (or end of file).
The text is stored in lineptr, including the delimiter character
and a terminating null. Like getline
, getdelim
makes
lineptr bigger if it isn't big enough.
getline
is in fact implemented in terms of getdelim
, just
like this:
ssize_t getline (char **lineptr, size_t *n, FILE *stream) { return getdelim (lineptr, n, '\n', stream); }
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
.
gets
reads characters from the stream stdin
up to the next newline character, and stores them in the string s.
The newline character is discarded (note that this differs from the
behavior of fgets
, which copies the newline character into the
string). If gets
encounters a read error or end-of-file, it
returns a null pointer; otherwise it returns s.
Warning: The gets
function is very dangerous
because it provides no protection against overflowing the string
s. The GNU library includes it for compatibility only. You
should always use fgets
or getline
instead. To
remind you of this, the linker (if using GNU ld
) will issue a
warning whenever you use gets
.
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.
ungetc
to do unreading.
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'.
ungetc
To Do Unreading
The function to unread a character is called ungetc
, because it
reverses the action of getc
.
ungetc
function pushes back the character c onto the
input stream stream. So the next input from stream will
read c before anything else.
If c is EOF
, ungetc
does nothing and just returns
EOF
. This lets you call ungetc
with the return value of
getc
without needing to check for an error from getc
.
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 7.15 File Positioning) is
called, any pending pushed-back characters are discarded.
Unreading a character on a stream that is at end of file clears the end-of-file indicator for the stream, because it makes the character of input available. After you read that character, trying to read again will encounter end of file.
Here is an example showing the use of 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> #include <ctype.h> void skip_whitespace (FILE *stream) { int c; do /* No need to check forEOF
because it is notisspace
, andungetc
ignoresEOF
. */ c = getc (stream); while (isspace (c)); ungetc (c, stream); }
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'.
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.
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.
vprintf
and friends.
parse_printf_format
.
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.
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 18 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:
int
.
If the value is negative, this means to set the `-' flag (see
below) and to use the absolute value as the field width.
int
, and is ignored
if it is negative. If you specify `*' for both the field width and
precision, the field width argument precedes the precision argument.
Other C library versions may not recognize this syntax.
int
,
but you can specify `h', `l', or `L' for other integer
types.)
The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they use.
With the `-Wformat' option, the GNU C compiler checks calls to
printf
and related functions. It examines the format string and
verifies that the correct number and types of arguments are supplied.
There is also a GNU C syntax to tell the compiler that a function you
write uses a printf
-style format string.
See section `Declaring Attributes of Functions' in Using GNU CC, for more information.
Here is a table summarizing what all the different conversions do:
scanf
for input
(see section 7.12.3 Table of Input Conversions).
errno
.
(This is a GNU extension.)
See section 7.10.6 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.
This section describes the options for the `%d', `%i', `%o', `%u', `%x', and `%X' conversion specifications. These conversions print integers in various formats.
The `%d' and `%i' conversion specifications both print an
int
argument as a signed decimal number; while `%o',
`%u', and `%x' print the argument as an unsigned octal,
decimal, or hexadecimal number (respectively). The `%X' conversion
specification is just like `%x' except that it uses the characters
`ABCDEF' as digits instead of `abcdef'.
The following flags are meaningful:
strtoul
function (see section 14.7.1 Parsing of Integers) and scanf
with the `%i' conversion
(see section 7.12.4 Numeric Input Conversions).
LC_NUMERIC
category; see section 19.6.1 Generic Numeric Formatting Parameters. This flag is a
GNU extension.
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:
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.
long int
or unsigned long
int
, as appropriate. Two `l' characters is like the `L'
modifier, below.
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 `q' modifier is another name for the same thing, which comes
from 4.4 BSD; a long long int
is sometimes called a "quad"
int
.
size_t
. This is a GNU extension.
Here is an example. Using the template string:
"|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
to print numbers using the different options for the `%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|
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:
LC_NUMERIC
category;
see section 19.6.1 Generic Numeric Formatting Parameters. This flag is a GNU extension.
The precision specifies how many digits follow the decimal-point
character for the `%f', `%e', and `%E' conversions. For
these conversions, the default precision is 6
. If the precision
is explicitly 0
, this suppresses the decimal point character
entirely. For the `%g' and `%G' conversions, the precision
specifies how many significant digits to print. Significant digits are
the first digit before the decimal point, and all the digits after it.
If the precision 0
or not specified for `%g' or `%G',
it is treated like a value of 1
. If the value being printed
cannot be expressed accurately in the specified number of digits, the
value is rounded to the nearest number that fits.
Without a type modifier, the floating-point conversions use an argument
of type double
. (By the default argument promotions, any
float
arguments are automatically converted to double
.)
The following type modifier is supported:
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.
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 *
(or const 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 2.3 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.
This section describes how to call printf
and related functions.
Prototypes for these functions are in the header file `stdio.h'.
Because these functions take a variable number of arguments, you
must declare prototypes for them before using them. Of course,
the easiest way to make sure you have all the right prototypes is to
just include `stdio.h'.
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.
printf
, except that the output is
written to the stream stream instead of stdout
.
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 5.4 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.
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 - 1
, 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.
The functions in this section do formatted output and place the results in dynamically allocated memory.
sprintf
, except that it dynamically
allocates a string (as with malloc
; see section 3.3 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 asprintf
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; }
asprintf
, except that it uses the
obstack obstack to allocate the space. See section 3.4 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 3.4.6 Growing Objects).
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."
When it is sufficient to define a macro rather than a real function, the GNU C compiler provides a way to do this much more easily with macros. For example:
#define myprintf(a, b, c, d, e, rest...) printf (mytemplate , ## rest...)
See section `Macros with Variable Numbers of Arguments' in Using GNU CC, for details. But this is limited to macros, and does not apply to real functions at all.
Before calling vprintf
or the other functions listed in this
section, you must call va_start
(see section 28.14 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 vprintf
does not
destroy the argument list of your function, merely the particular
pointer that you passed to it.
GNU C does not have such restrictions. You can safely continue to fetch
arguments from a va_list
pointer after passing it to
vprintf
, and va_end
is a no-op. (Note, however, that
subsequent va_arg
calls will fetch the same arguments which
vprintf
previously used.)
Prototypes for these functions are declared in `stdio.h'.
printf
except that, instead of taking
a variable number of arguments directly, it takes an argument list
pointer ap.
fprintf
with the variable argument list
specified directly as for vprintf
.
sprintf
with the variable argument list
specified directly as for vprintf
.
snprintf
with the variable argument list
specified directly as for vprintf
.
vasprintf
function is the equivalent of asprintf
with the
variable argument list specified directly as for vprintf
.
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 2.3 Error Messages, for a description of
program_invocation_short_name
).
#include <stdio.h> #include <stdarg.h> void eprintf (const char *template, ...) { va_list ap; extern char *program_invocation_short_name; fprintf (stderr, "%s: ", program_invocation_short_name); va_start (ap, count); vfprintf (stderr, template, ap); va_end (ap); }
You could call eprintf
like this:
eprintf ("file `%s' does not exist\n", filename);
In GNU C, there is a special construct you can use to let the compiler
know that a function uses a printf
-style format string. Then it
can check the number and types of arguments in each call to the
function, and warn you when they do not match the format string.
For example, take this declaration of eprintf
:
void eprintf (const char *template, ...) __attribute__ ((format (printf, 1, 2)));
This tells the compiler that eprintf
uses a format string like
printf
(as opposed to scanf
; see section 7.12 Formatted Input);
the format string appears as the first argument;
and the arguments to satisfy the format begin with the second.
See section `Declaring Attributes of Functions' in Using GNU CC, for more information.
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'.
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.
(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
int
.
PA_CHAR
int
, cast to char
.
PA_STRING
char *
, a null-terminated string.
PA_POINTER
void *
, an arbitrary pointer.
PA_FLOAT
float
.
PA_DOUBLE
double
.
PA_LAST
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
PA_FLAG_SHORT
short
. (This corresponds to the `h' type modifier.)
PA_FLAG_LONG
long
. (This corresponds to the `l' type modifier.)
PA_FLAG_LONG_LONG
long long
. (This corresponds to the `L' type modifier.)
PA_FLAG_LONG_DOUBLE
PA_FLAG_LONG_LONG
, used by convention with
a base type of PA_DOUBLE
to indicate a type of long double
.
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 *argtypes; int nwanted; /* Get the information about the arguments. Each conversion specification must be at least two characters long, so there cannot be more specifications than half the length of the string. */ argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int)); nwanted = parse_printf_format (string, nelts, argtypes); /* Check the number of arguments. */ if (nwanted > nargs) { error ("too few arguments (at least %d required)", nwanted); return 0; } /* Check the C type wanted for each argument and see if the object given is suitable. */ for (i = 0; i < nwanted; i++) { int wanted; if (argtypes[i] & PA_FLAG_PTR) wanted = STRUCTURE; else switch (argtypes[i] & ~PA_FLAG_MASK) { case PA_INT: case PA_FLOAT: case PA_DOUBLE: wanted = NUMBER; break; case PA_CHAR: wanted = CHAR; break; case PA_STRING: wanted = STRING; break; case PA_POINTER: wanted = STRUCTURE; break; } if (TYPE (args[i]) != wanted) { error ("type mismatch for arg number %d", i); return 0; } } return 1; }
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 the function
register_printf_function
; see section 7.11.1 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 7.11.3 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 7.10.10 Parsing a Template String, for information about this.
The facilities of this section are declared in the header file `printf.h'.
register_printf_function
to register a new output conversion.
register_printf_function
.
printf
handler function.
Portability Note: The ability to extend the syntax of
printf
template strings is a GNU extension. ISO standard C has
nothing similar.
The function to register a new output conversion is
register_printf_function
, declared in `printf.h'.
'z'
, it defines the conversion `%z'.
You can redefine the built-in conversions like `%s', but flag
characters like `#' and type modifiers like `l' can never be
used as conversions; calling register_printf_function
for those
characters has no effect.
The handler-function is the function called by printf
and
friends when this conversion appears in a template string.
See section 7.11.3 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 7.10.10 Parsing a Template String, for information
about this.
Attention: In the GNU C library version before 2.0 the
arginfo-function function did not need to be installed unless
the user uses the parse_printf_format
function. This changed.
Now a call to any of the printf
functions will call this
function when this format specifier appears in the format string.
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.
If you define a meaning for `%A', what if the template contains `%+23A' or `%-#A'? To implement a sensible meaning for these, the handler when called needs to be able to get the options specified in the template.
Both the handler-function and arginfo-function arguments
to register_printf_function
accept an argument that points to a
struct printf_info
, which contains information about the options
appearing in an instance of the conversion specifier. This data type
is declared in the header file `printf.h'.
printf
template
string to the handler and arginfo functions for that specifier. It
contains the following members:
int prec
-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
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.
wchar_t spec
unsigned int is_long_double
long long int
, as opposed to long double
for floating
point conversions.
unsigned int is_short
unsigned int is_long
unsigned int alt
unsigned int space
unsigned int left
unsigned int showsign
unsigned int group
unsigned int extra
printf
function this variable always contains the value
0
.
wchar_t pad
'0'
if the `0' flag was specified, and
' '
otherwise.
Now let's look at how to define the handler and arginfo functions
which are passed as arguments to register_printf_function
.
Compatibility Note: The interface change in the GNU libc
version 2.0. Previously the third argument was of type
va_list *
.
You should define your handler functions with a prototype like:
int function (FILE *stream, const struct printf_info *info, const void *const *args)
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 7.11.2 Conversion Specifier Options, for a description of this data structure.
The args is a vector of pointers to the arguments data. The number of arguments were determined by calling the argument information function provided by the user.
Your handler function should return a value just like printf
does: it should return the number of characters it has written, or a
negative value to indicate an error.
If you are going to use parse_printf_format
in your
application, you must also define a function to pass as the
arginfo-function argument for each new conversion you install with
register_printf_function
.
You have to 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. The function should also fill in no more than
n elements of 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.)
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 print_widget_arginfo (const struct printf_info *info, size_t n, int *argtypes) { /* We always take exactly one argument and this is a pointer to the structure.. */ if (n > 0) argtypes[0] = PA_POINTER; return 1; } int main (void) { /* Make a widget to print. */ Widget mywidget; mywidget.name = "mywidget"; /* Register the print function for widgets. */ register_printf_function ('W', print_widget, print_widget_arginfo); /* Now print the widget. */ printf ("|%W|\n", &mywidget); printf ("|%35W|\n", &mywidget); printf ("|%-35W|\n", &mywidget); return 0; }
The output produced by this program looks like:
|<Widget 0xffeffb7c: mywidget>| | <Widget 0xffeffb7c: mywidget>| |<Widget 0xffeffb7c: mywidget> |
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.
malloc
the buffer.
vscanf
and friends.
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 Flex to generate a
lexical scanner, or Bison to generate a parser, rather than using
scanf
. For more information about these tools, see section `' in Flex: The Lexical Scanner Generator, and section `' in The Bison Reference Manual.
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 4.1 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:
scanf
finds a conversion
specification that uses this flag, it reads input as directed by the
rest of the conversion specification, but it discards this input, does
not use a pointer argument, and does not increment the count of
successful assignments.
long int
rather than a pointer to an int
.
The exact options that are permitted and how they are interpreted vary between the different conversion specifiers. See the descriptions of the individual conversions for information about the particular options that they allow.
With the `-Wformat' option, the GNU C compiler checks calls to
scanf
and related functions. It examines the format string and
verifies that the correct number and types of arguments are supplied.
There is also a GNU C syntax to tell the compiler that a function you
write uses a scanf
-style format string.
See section `Declaring Attributes of Functions' in Using GNU CC, for more information.
Here is a table that summarizes the various conversion specifications:
printf
. See section 7.12.7 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.
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 14.7.1 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 14.7.1 Parsing of Integers) with the value
0
for the base argument. (You can print integers in this
syntax with printf
by using the `#' flag character with the
`%x', `%o', or `%d' conversion. See section 7.10.4 Integer Conversions.)
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 14.7.1 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:
short int *
or unsigned
short int *
.
long int *
or unsigned
long int *
. Two `l' characters is like the `L' modifier, below.
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
.)
The `q' modifier is another name for the same thing, which comes
from 4.4 BSD; a long long int
is sometimes called a "quad"
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 14.7.2 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:
double *
.
long double *
.
For all the above number parsing formats there is an additional optional
flag `''. When this flag is given the scanf
function
expects the number represented in the input string to be formatted
according to the grouping rules of the currently selected locale
(see section 19.6.1 Generic Numeric Formatting Parameters).
If the "C"
or "POSIX"
locale is selected there is no
difference. But for a locale which specifies values for the appropriate
fields in the locale the input must have the correct form in the input.
Otherwise the longest prefix with a correct form is processed.
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:
char *
.
Warning: To make a robust program, you must make sure that the
input (plus its terminating null) cannot possibly exceed the size of the
buffer you provide. In general, the only way to do this is to specify a
maximum field width one less than the buffer size. If you
provide the buffer, always specify a maximum field width to prevent
overflow.
scanf
to allocate a big enough buffer, by specifying the
`a' flag character. This is a GNU extension. You should provide
an argument of type char **
for the buffer address to be stored
in. See section 7.12.6 Dynamically Allocating String 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:
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.
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; } ... }
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
(see section 7.10.6 Other Output Conversions); that is, a hexadecimal
number just as the `%x' conversion accepts. 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 7.10.6 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.
Here are the descriptions of the functions for performing formatted input. Prototypes for these functions are in the header file `stdio.h'.
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.
scanf
, except that the input is read
from the stream stream instead of stdin
.
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.
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 7.10.9 Variable Arguments Output Functions, for important
information on how to use them.
Portability Note: The functions listed in this section are GNU extensions.
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 28.14 Variadic Functions).
fscanf
with the variable argument list
specified directly as for vscanf
.
sscanf
with the variable argument list
specified directly as for vscanf
.
In GNU C, there is a special construct you can use to let the compiler
know that a function uses a scanf
-style format string. Then it
can check the number and types of arguments in each call to the
function, and warn you when they do not match the format string.
See section `Declaring Attributes of Functions' in Using GNU CC, for details.
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'.
EOF
is -1
. In other libraries, its
value may be some other negative number.
The file positioning functions (see section 7.15 File Positioning) also clear the end-of-file indicator for the stream.
feof
function returns nonzero if and only if the end-of-file
indicator for the stream stream is set.
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 8 Low-Level Input/Output.
The GNU system and other POSIX-compatible operating systems organize all files as uniform sequences of characters. However, some other systems make a distinction between files containing text and files containing binary data, and the input and output facilities of ISO C provide for this distinction. This section tells you how to write programs portable to such systems.
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 7.3 Opening Streams. Without this
option, fopen
opens the file as a text stream.
Text and binary streams differ in several ways:
'\n'
) characters, while a binary stream is
simply a long series of characters. A text stream might on some systems
fail to handle lines more than 254 characters long (including the
terminating newline character).
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.
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 6.1.2 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'.
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.
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 7.14 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 8.2 Input and Output Primitives) and to specify offsets for file locks
(see section 8.7 Control Operations on Files).
fseek
function, specifies that the offset
provided is relative to the beginning of the file.
fseek
function, specifies that the offset
provided is relative to the current file position.
fseek
function, specifies that the offset
provided is relative to the end of the file.
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
SEEK_SET
.
L_INCR
SEEK_CUR
.
L_XTND
SEEK_END
.
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 ISO C
systems do not represent file positions in this way.
On some systems where text streams truly differ from binary streams, it is impossible to represent the file position of a text stream as a count of characters from the beginning of the file. For example, the file position on some systems must encode both a record offset within the file, and a character offset within the record.
As a consequence, if you want your programs to be portable to these systems, you must observe certain rules:
ftell
on a text stream has no predictable
relationship to the number of characters you have read so far. The only
thing you can rely on is that you can use it subsequently as the
offset argument to fseek
to move back to the same file
position.
fseek
on a text stream, either the offset must
either be zero; or whence must be SEEK_SET
and the
offset must be the result of an earlier call to ftell
on
the same stream.
ungetc
that haven't been read or discarded. See section 7.8 Unreading.
But even if you observe these rules, you may still have trouble for long
files, because ftell
and fseek
use a long int
value
to represent the file position. This type may not have room to encode
all the file positions in a large file.
So if you do want to support systems with peculiar encodings for the
file positions, it is better to use the functions fgetpos
and
fsetpos
instead. These functions represent the file position
using the data type fpos_t
, whose internal representation varies
from system to system.
These symbols are declared in the header file `stdio.h'.
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.
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
.
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
.
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 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 12 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 8 Low-Level Input/Output.
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 7.17.3 Controlling Which Kind of Buffering, for information on how to select a different kind of buffering. Usually the automatic selection gives you the most convenient kind of buffering for the file or device you open.
The use of line buffering for interactive devices implies that output
messages ending in a newline will appear immediately--which is usually
what you want. Output that doesn't end in a newline might or might not
show up immediately, so if you want them to appear immediately, you
should flush buffered output explicitly with fflush
, as described
in section 7.17.2 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:
exit
.
See section 22.3.1 Normal Termination.
If you want to flush the buffered output at another time, call
fflush
, which is declared in the header file `stdio.h'.
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.
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'.
_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 3.3 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.
setvbuf
function to
specify that the stream should be fully buffered.
setvbuf
function to
specify that the stream should be line buffered.
setvbuf
function to
specify that the stream should be unbuffered.
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 9.8.1 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 7.6 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.
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.
This function is provided for compatibility with old BSD code. Use
setvbuf
instead.
This function is provided for compatibility with old BSD code. Use
setvbuf
instead.
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 7.18.1 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 7.18.3 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.
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'.
If you specify a null pointer as the buf argument, fmemopen
dynamically allocates (as with malloc
; see section 3.3 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 7.3 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
malloc
; see section 3.3 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 7.15 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
You can open an output stream that puts it data in an obstack. See section 3.4 Obstacks.
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 7.15 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 3.4.8 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); }
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.
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
cookie_io_functions_t
.
These facilities are declared in `stdio.h'.
cookie_read_function_t *read
EOF
.
cookie_write_function_t *write
cookie_seek_function_t *seek
fseek
on this stream can only seek to locations within the
buffer; any attempt to seek outside the buffer will return an
ESPIPE
error.
cookie_close_function_t *close
fopen
;
see section 7.3 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.
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 8.2 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 8.2 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 7.16 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.
Go to the first, previous, next, last section, table of contents.