
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.
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 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 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 Opening Streams.
The three streams stdin, stdout, and stderr are not
unoriented at program start (see section Streams in Internationalized Applications).
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 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 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 are guaranteed that
you will not clobber an existing file. This is equivalent to the
O_EXCL option to the open function (see section 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 Text and Binary Streams.
If the opentype string contains the sequence
,ccs=STRING then STRING is taken as the name of a
coded character set and fopen will mark the stream as
wide-oriented which appropriate conversion functions in place to convert
from and to the character set STRING is place. Any other stream
is opened initially unoriented and the orientation is decided with the
first file operation. If the first operation is a wide character
operation, the stream is not only marked as wide-oriented, also the
conversion functions to convert to the coded character set used for the
current locale are loaded. This will not change anymore from this point
on even if the locale selected for the LC_CTYPE category is
changed.
Any other characters in opentype are simply ignored. They may be meaningful in other systems.
If the open fails, fopen returns a null pointer.
When the sources are compiling with _FILE_OFFSET_BITS == 64 on a
32 bit machine this function is in fact fopen64 since the LFS
interface replaces transparently the old interface.
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 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 File Locks.
fopen but the stream it returns a
pointer for is opened using open64. Therefore this stream can be
used even on files larger then @math{2^31} bytes on 32 bit machines.
Please note that the return type is still FILE *. There is no
special FILE type for the LFS interface.
If the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32
bits machine this function is available under the name fopen
and so transparently replaces the old interface.
stdin, stdout, and stderr. In POSIX.1 systems this
value is determined by the OPEN_MAX parameter; see section General Capacity Limits. In BSD and GNU, it is controlled by the RLIMIT_NOFILE
resource limit; see section 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 the sources are compiling with _FILE_OFFSET_BITS == 64 on a
32 bit machine this function is in fact freopen64 since the LFS
interface replaces transparently the old interface.
freopen. The only difference is that
on 32 bit machine the stream returned is able to read beyond the
@math{2^31} bytes limits imposed by the normal interface. It should be
noted that the stream pointed to by stream need not be opened
using fopen64 or freopen64 since its mode is not important
for this function.
If the sources are compiled with _FILE_OFFSET_BITS == 64 on a 32
bits machine this function is available under the name freopen
and so transparently replaces the old interface.
In some situations it is useful to know whether a given stream is available for reading or writing. This information is normally not available and would have to be remembered separately. Solaris introduced a few functions to get this information from the stream descriptor and these functions are also available in the GNU C library.
__freadable function determines whether the stream
stream was opened to allow reading. In this case the return value
is nonzero. For write-only streams the function returns zero.
This function is declared in `stdio_ext.h'.
__fwritable function determines whether the stream
stream was opened to allow writing. In this case the return value
is nonzero. For read-only streams the function returns zero.
This function is declared in `stdio_ext.h'.
For slightly different kind of problems there are two more functions. They provide even finer-grained information.
__freading function determines whether the stream
stream was last read from or whether it is opened read-only. In
this case the return value is nonzero, otherwise it is zero.
Determining whether a stream opened for reading and writing was last
used for writing allows to draw conclusions about the content about the
buffer, among other things.
This function is declared in `stdio_ext.h'.
__fwriting function determines whether the stream
stream was last written to or whether it is opened write-only. In
this case the return value is nonzero, otherwise it is zero.
This function is declared in `stdio_ext.h'.
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 only in special situations, e.g., when an error occurred and the program must be aborted. Normally each single stream should be closed separately so that problems with individual streams can be identified. It is also problematic since the standard streams (see section 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 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 might not be flushed and
files may be incomplete. For more information on buffering of streams,
see section Stream Buffering.
Streams can be used in multi-threaded applications in the same way they are used in single-threaded applications. But the programmer must be aware of a the possible complications. It is important to know about these also if the program one writes never use threads since the design and implementation of many stream functions is heavily influenced by the requirements added by multi-threaded programming.
The POSIX standard requires that by default the stream operations are atomic. I.e., issueing two stream operations for the same stream in two threads at the same time will cause the operations to be executed as if they were issued sequentially. The buffer operations performed while reading or writing are protected from other uses of the same stream. To do this each stream has an internal lock object which has to be (implicitly) acquired before any work can be done.
But there are situations where this is not enough and there are also situations where this is not wanted. The implicit locking is not enough if the program requires more than one stream function call to happen atomically. One example would be if an output line a program wants to generate is created by several function calls. The functions by themselves would ensure only atomicity of their own operation, but not atomicity over all the function calls. For this it is necessary to perform the stream locking in the application code.
flockfile function acquires the internal locking object
associated with the stream stream. This ensures that no other
thread can explicitly through flockfile/ftrylockfile or
implicit through a call of a stream function lock the stream. The
thread will block until the lock is acquired. An explicit call to
funlockfile has to be used to release the lock.
ftrylockfile function tries to acquire the internal locking
object associated with the stream stream just like
flockfile. But unlike flockfile this function does not
block if the lock is not available. ftrylockfile returns zero if
the lock was successfully acquired. Otherwise the stream is locked by
another thread.
funlockfile function releases the internal locking object of
the stream stream. The stream must have been locked before by a
call to flockfile or a successful call of ftrylockfile.
The implicit locking performed by the stream operations do not count.
The funlockfile function does not return an error status and the
behavior of a call for a stream which is not locked by the current
thread is undefined.
The following example shows how the functions above can be used to
generate an output line atomically even in multi-threaded applications
(yes, the same job could be done with one fprintf call but it is
sometimes not possible):
FILE *fp;
{
...
flockfile (fp);
fputs ("This is test number ", fp);
fprintf (fp, "%d\n", test);
funlockfile (fp)
}
Without the explicit locking it would be possible for another thread to
use the stream fp after the fputs call return and before
fprintf was called with the result that the number does not
follow the word `number'.
From this description it might already be clear that the locking objects
in streams are no simple mutexes. Since locking the same stream twice
in the same thread is allowed the locking objects must be equivalent to
recursive mutexes. These mutexes keep track of the owner and the number
of times the lock is acquired. The same number of funlockfile
calls by the same threads is necessary to unlock the stream completely.
For instance:
void
foo (FILE *fp)
{
ftrylockfile (fp);
fputs ("in foo\n", fp);
/* This is very wrong!!! */
funlockfile (fp);
}
It is important here that the funlockfile function is only called
if the ftrylockfile function succeeded in locking the stream. It
is therefore always wrong to ignore the result of ftrylockfile.
And it makes no sense since otherwise one would use flockfile.
The result of code like that above is that either funlockfile
tries to free a stream that hasn't been locked by the current thread or it
frees the stream prematurely. The code should look like this:
void
foo (FILE *fp)
{
if (ftrylockfile (fp) == 0)
{
fputs ("in foo\n", fp);
funlockfile (fp);
}
}
Now that we covered why it is necessary to have these locking it is necessary to talk about situations when locking is unwanted and what can be done. The locking operations (explicit or implicit) don't come for free. Even if a lock is not taken the cost is not zero. The operations which have to be performed require memory operations which are save in multi-processor environments. With the many local caches involved in such systems this is quite costly. So it is best to avoid the locking completely if it is known that the code using the stream is never used in a context where more than one thread can use the stream at one time. This can be determined most of the time for application code; for library code which can be used in many contexts one should default to be conservative and use locking.
There are two basic mechanisms to avoid locking. The first is to use
the _unlocked variants of the stream operations. The POSIX
standard defines quite a few of those and the GNU library adds a few
more. These variants of the functions behave just like the functions
with the name without the suffix except that they are not locking the
stream. Using these functions is very desirable since they are
potentially much faster. This is not only because the locking
operation itself is avoided. More importantly, functions like
putc and getc are very simple and tradionally (before the
introduction of threads) were implemented as macros which are very fast
if the buffer is not empty. With locking required these functions are
now no macros anymore (the code generated would be too much). But these
macros are still available with the same functionality under the new
names putc_unlocked and getc_unlocked. This possibly huge
difference of speed also suggests the use of the _unlocked
functions even if locking is required. The difference is that the
locking then has to be performed in the program:
void
foo (FILE *fp, char *buf)
{
flockfile (fp);
while (*buf != '/')
putc_unlocked (*buf++, fp);
funlockfile (fp);
}
If in this example the putc function would be used and the
explicit locking would be missing the putc function would have to
acquire the lock in every call, potentially many times depending on when
the loop terminates. Writing it the way illustrated above allows the
putc_unlocked macro to be used which means no locking and direct
manipulation of the buffer of the stream.
A second way to avoid locking is by using a non-standard function which was introduced in Solaris and is available in the GNU C library as well.
The __fsetlocking function can be used to select whether the
stream operations will implicitly acquire the locking object of the
stream stream. By default this is done but it can be disabled and
reinstated using this function. There are three values defined for the
type parameter.
FSETLOCKING_INTERNAL
stream will from now on use the default internal
locking. Every stream operation with exception of the _unlocked
variants will implicitly lock the stream.
FSETLOCKING_BYCALLER
__fsetlocking function returns the user is responsible
for locking the stream. None of the stream operations will implicitly
do this anymore until the state is set back to
FSETLOCKING_INTERNAL.
FSETLOCKING_QUERY
__fsetlocking only queries the current locking state of the
stream. The return value will be FSETLOCKING_INTERNAL or
FSETLOCKING_BYCALLER depending on the state.
The return value of __fsetlocking is either
FSETLOCKING_INTERNAL or FSETLOCKING_BYCALLER depending on
the state of the stream before the call.
This function and the values for the type parameter are declared in `stdio_ext.h'.
This function is especially useful when program code has to be used
which is written without knowledge about the _unlocked functions
(or if the programmer was to lazy to use them).
ISO C90 introduced the new type wchar_t to allow handling
larger character sets. What was missing was a possibility to output
strings of wchar_t directly. One had to convert them into
multibyte strings using mbstowcs (there was no mbsrtowcs
yet) and then use the normal stream functions. While this is doable it
is very cumbersome since performing the conversions is not trivial and
greatly increases program complexity and size.
The Unix standard early on (I think in XPG4.2) introduced two additional
format specifiers for the printf and scanf families of
functions. Printing and reading of single wide characters was made
possible using the %C specifier and wide character strings can be
handled with %S. These modifiers behave just like %c and
%s only that they expect the corresponding argument to have the
wide character type and that the wide character and string are
transformed into/from multibyte strings before being used.
This was a beginning but it is still not good enough. Not always is it
desirable to use printf and scanf. The other, smaller and
faster functions cannot handle wide characters. Second, it is not
possible to have a format string for printf and scanf
consisting of wide characters. The result is that format strings would
have to be generated if they have to contain non-basic characters.
In the Amendment 1 to ISO C90 a whole new set of functions was
added to solve the problem. Most of the stream functions got a
counterpart which take a wide character or wide character string instead
of a character or string respectively. The new functions operate on the
same streams (like stdout). This is different from the model of
the C++ runtime library where separate streams for wide and normal I/O
are used.
Being able to use the same stream for wide and normal operations comes
with a restriction: a stream can be used either for wide operations or
for normal operations. Once it is decided there is no way back. Only a
call to freopen or freopen64 can reset the
orientation. The orientation can be decided in three ways:
fread and fwrite functions) the stream is marked as not
wide oriented.
fwide function can be used to set the orientation either way.
It is important to never mix the use of wide and not wide operations on
a stream. There are no diagnostics issued. The application behavior
will simply be strange or the application will simply crash. The
fwide function can help avoiding this.
The fwide function can be used to set and query the state of the
orientation of the stream stream. If the mode parameter has
a positive value the streams get wide oriented, for negative values
narrow oriented. It is not possible to overwrite previous orientations
with fwide. I.e., if the stream stream was already
oriented before the call nothing is done.
If mode is zero the current orientation state is queried and nothing is changed.
The fwide function returns a negative value, zero, or a positive
value if the stream is narrow, not at all, or wide oriented
respectively.
This function was introduced in Amendment 1 to ISO C90 and is declared in `wchar.h'.
It is generally a good idea to orient a stream as early as possible.
This can prevent surprise especially for the standard streams
stdin, stdout, and stderr. If some library
function in some situations uses one of these streams and this use
orients the stream in a different way the rest of the application
expects it one might end up with hard to reproduce errors. Remember
that no errors are signal if the streams are used incorrectly. Leaving
a stream unoriented after creation is normally only necessary for
library functions which create streams which can be used in different
contexts.
When writing code which uses streams and which can be used in different contexts it is important to query the orientation of the stream before using it (unless the rules of the library interface demand a specific orientation). The following little, silly function illustrates this.
void
print_f (FILE *fp)
{
if (fwide (fp, 0) > 0)
/* Positive return value means wide orientation. */
fputwc (L'f', fp);
else
fputc ('f', fp);
}
Note that in this case the function print_f decides about the
orientation of the stream if it was unoriented before (will not happen
if the advise above is followed).
The encoding used for the wchar_t values is unspecified and the
user must not make any assumptions about it. For I/O of wchar_t
values this means that it is impossible to write these values directly
to the stream. This is not what follows from the ISO C locale model
either. What happens instead is that the bytes read from or written to
the underlying media are first converted into the internal encoding
chosen by the implementation for wchar_t. The external encoding
is determined by the LC_CTYPE category of the current locale or
by the `ccs' part of the mode specification given to fopen,
fopen64, freopen, or freopen64. How and when the
conversion happens is unspecified and it happens invisible to the user.
Since a stream is created in the unoriented state it has at that point
no conversion associated with it. The conversion which will be used is
determined by the LC_CTYPE category selected at the time the
stream is oriented. If the locales are changed at the runtime this
might produce surprising results unless one pays attention. This is
just another good reason to orient the stream explicitly as soon as
possible, perhaps with a call to fwide.
This section describes functions for performing character- and line-oriented output.
These narrow streams functions are declared in the header file `stdio.h' and the wide stream functions in `wchar.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.
fputwc function writes the wide character wc to the
stream stream. WEOF is returned if a write error occurs;
otherwise the character wc is returned.
fputc_unlocked function is equivalent to the fputc
function except that it does not implicitly lock the stream.
fputwc_unlocked function is equivalent to the fputwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.
fputwc, except that it can be implement 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. putwc is usually the best function to
use for writing a single wide character.
putc_unlocked function is equivalent to the putc
function except that it does not implicitly lock the stream.
putwc_unlocked function is equivalent to the putwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
putchar function is equivalent to putc with
stdout as the value of the stream argument.
putwchar function is equivalent to putwc with
stdout as the value of the stream argument.
putchar_unlocked function is equivalent to the putchar
function except that it does not implicitly lock the stream.
putwchar_unlocked function is equivalent to the putwchar
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.
fputws writes the wide character string ws 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 WEOF if a write error occurs, and otherwise
a non-negative value.
fputs_unlocked function is equivalent to the fputs
function except that it does not implicitly lock the stream.
This function is a GNU extension.
fputws_unlocked function is equivalent to the fputws
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.");
outputs the text `This is a message.' followed by a newline.
int) to
stream. It is provided for compatibility with SVID, but we
recommend you use fwrite instead (see section Block Input/Output).
This section describes functions for performing character-oriented input. These narrow streams functions are declared in the header file `stdio.h' and the wide character functions are declared in `wchar.h'.
These functions return an int or wint_t value (for narrow
and wide stream functions respectively) that is either a character of
input, or the special value EOF/WEOF (usually -1). For
the narrow stream functions 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.
WEOF is returned instead.
fgetc_unlocked function is equivalent to the fgetc
function except that it does not implicitly lock the stream.
fgetwc_unlocked function is equivalent to the fgetwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.
fgetwc, except that it is permissible for it to
be implemented as a macro that evaluates the stream argument more
than once. getwc can be highly optimized, so it is usually the
best function to use to read a single wide character.
getc_unlocked function is equivalent to the getc
function except that it does not implicitly lock the stream.
getwc_unlocked function is equivalent to the getwc
function except that it does not implicitly lock the stream.
This function is a GNU extension.
getchar function is equivalent to getc with stdin
as the value of the stream argument.
getwchar function is equivalent to getwc with stdin
as the value of the stream argument.
getchar_unlocked function is equivalent to the getchar
function except that it does not implicitly lock the stream.
getwchar_unlocked function is equivalent to the getwchar
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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). The code would
also work the same for the wide character stream functions.
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 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 is 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 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 without any bytes read,
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.
fgetws function reads wide characters from the stream
stream up to and including a newline character and stores them in
the string ws, adding a null wide character to mark the end of the
string. You must supply count wide characters worth of space in
ws, but the number of characters read is at most count
- 1. The extra character space is used to hold the null wide
character at the end of the string.
If the system is already at end of file when you call fgetws, then
the contents of the array ws 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 ws.
Warning: If the input data has a null wide character (which are
null bytes in the input stream), you can't tell. So don't use
fgetws 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.
fgets_unlocked function is equivalent to the fgets
function except that it does not implicitly lock the stream.
This function is a GNU extension.
fgetws_unlocked function is equivalent to the fgetws
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.
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, fseeko 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. After you read that character, trying to read again will encounter end of file.
ungetwc function behaves just like ungetc just that it
pushes back a wide character.
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 for EOF because it is not
isspace, and ungetc ignores EOF. */
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.
fread_unlocked function is equivalent to the fread
function except that it does not implicitly lock the stream.
This function is a GNU extension.
fwrite_unlocked function is equivalent to the fwrite
function except that it does not implicitly lock the stream.
This function is a GNU extension.
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.
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 Character Set Handling) are permitted in a template string.
The conversion specifications in a printf template string have
the general form:
% [ param-no $] 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:
printf function are assigned to the
formats in the order of appearance in the format string. But in some
situations (such as message translation) this is not desirable and this
extension allows an explicit parameter to be specified.
The param-no part of the format must be an integer in the range of
1 to the maximum number of arguments present to the function call. Some
implementations limit this number to a certainly upper bound. The exact
limit can be retrieved by the following constant.
ARGMAX is the maximum value allowed for the
specification of an positional parameter in a printf call. The
actual value in effect at runtime can be retrieved by using
sysconf using the _SC_NL_ARGMAX parameter see section Definition of sysconf.
Some system have a quite low limit such as @math{9} for System V
systems. The GNU C library has no real limit.
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 Table of Input Conversions).
errno.
(This is a GNU extension.)
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.
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 Parsing of Integers) and scanf with the `%i' conversion
(see section Numeric Input Conversions).
LC_NUMERIC category; see section 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:
signed char or unsigned
char, as appropriate. A char 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
char again.
This modifier was introduced in ISO C99.
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.
intmax_t or uintmax_t, as
appropriate.
This modifier was introduced in ISO C99.
long int or unsigned long
int, as appropriate. Two `l' characters is like the `L'
modifier, below.
If used with `%c' or `%s' the corresponding parameter is
considered as a wide character or wide character string respectively.
This use of `l' was introduced in Amendment 1 to ISO C90.
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.
ptrdiff_t.
This modifier was introduced in ISO C99.
size_t.
`z' was introduced in ISO C99. `Z' is a GNU extension
predating this addition and should not be used in new code.
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 `%a' and `%A' conversions are meant for representing
floating-point numbers exactly in textual form so that they can be
exchanged as texts between different programs and/or machines. The
numbers are represented is the form
[-]0xh.hhhp[+|-]dd.
At the left of the decimal-point character exactly one digit is print.
This character is only 0 if the number is denormalized.
Otherwise the value is unspecified; it is implementation dependent how many
bits are used. The number of hexadecimal digits on the right side of
the decimal-point character is equal to the precision. If the precision
is zero it is determined to be large enough to provide an exact
representation of the number (or it is large enough to distinguish two
adjacent values if the FLT_RADIX is not a power of 2,
see section Floating Point Parameters). For the `%a' conversion
lower-case characters are used to represent the hexadecimal number and
the prefix and exponent sign are printed as 0x and p
respectively. Otherwise upper-case characters are used and 0X
and P are used for the representation of prefix and exponent
string. The exponent to the base of two is printed as a decimal number
using at least one digit but at most as many digits as necessary to
represent the value exactly.
If the value to be printed represents infinity or a NaN, the output is
[-]inf or nan respectively if the conversion
specifier is `%a', `%e', `%f', or `%g' and it is
[-]INF or NAN respectively if the conversion is
`%A', `%E', or `%G'.
The following flags can be used to modify the behavior:
LC_NUMERIC category;
see section 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 is 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:
"|%13.4a|%13.4f|%13.4e|%13.4g|\n"
Here is the output:
| 0x0.0000p+0| 0.0000| 0.0000e+00| 0| | 0x1.0000p-1| 0.5000| 5.0000e-01| 0.5| | 0x1.0000p+0| 1.0000| 1.0000e+00| 1| | -0x1.0000p+0| -1.0000| -1.0000e+00| -1| | 0x1.9000p+6| 100.0000| 1.0000e+02| 100| | 0x1.f400p+9| 1000.0000| 1.0000e+03| 1000| | 0x1.3880p+13| 10000.0000| 1.0000e+04| 1e+04| | 0x1.81c8p+13| 12345.0000| 1.2345e+04| 1.234e+04| | 0x1.86a0p+16| 100000.0000| 1.0000e+05| 1e+05| | 0x1.e240p+16| 123456.0000| 1.2346e+05| 1.235e+05|
Notice how the `%g' conversion drops trailing zeros.
This section describes miscellaneous conversions for printf.
The `%c' conversion prints a single character. In case there is no
`l' modifier the int argument is first converted to an
unsigned char. Then, if used in a wide stream function, the
character is converted into the corresponding wide character. 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'.
If there is a `l' modifier present the argument is expected to be
of type wint_t. If used in a multibyte function the wide
character is converted into a multibyte character before being added to
the output. In this case more than one output byte can be produced.
The `%s' conversion prints a string. If no `l' modifier is
present the corresponding argument must be of type char * (or
const char *). If used in a wide stream function the string is
first converted in a wide character string. 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 there is a `l' modifier present the argument is expected to be of type wchar_t (or const wchar_t *).
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.
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.
wprintf function prints the optional arguments under the
control of the wide template string template to the stream
stdout. It returns the number of wide 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.
wprintf, 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 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.
wprintf, except that the output is stored in the
wide character array ws instead of written to a stream. A null
wide character is written to mark the end of the string. 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 wide characters for the string ws.
The return value is the number of characters which would be generated for the given input, excluding the trailing null. If this value is greater or equal to size, not all characters from the result have been stored in ws. You should try again with a bigger output string.
Note that the corresponding narrow stream function takes fewer
parameters. swprintf in fact corresponds to the snprintf
function. Since the sprintf function can be dangerous and should
be avoided the ISO C committee refused to make the same mistake
again and decided to not define an function exactly corresponding to
sprintf.
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 which would be generated for the given input, excluding the trailing null. If this value is greater or equal to size, not all characters from the result have been stored in s. 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);
int nchars;
if (buffer == NULL)
return NULL;
/* Try to print in the allocated space. */
nchars = snprintf (buffer, size, "value of %s is %s",
name, value);
if (nchars >= size)
{
/* Reallocate buffer now that we know
how much space is needed. */
buffer = (char *) xrealloc (buffer, nchars + 1);
if (buffer != NULL)
/* Try again. */
snprintf (buffer, size, "value of %s is %s",
name, value);
}
/* The last call worked, return the string. */
return buffer;
}
In practice, it is often easier just to use asprintf, below.
Attention: In versions of the GNU C library prior to 2.1 the
return value is the number of characters stored, not including the
terminating null; unless there was not enough space in s to
store the result in which case -1 is returned. This was
changed in order to comply with the ISO C99 standard.
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 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.
The return value is the number of characters allocated for the buffer, or less than zero if an error occured. Usually this means that the buffer could not be allocated.
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;
if (asprintf (&result, "value of %s is %s", name, value) < 0)
return NULL;
return result;
}
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).
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 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.
wprintf 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.
fwprintf with the variable argument list
specified directly as for vwprintf.
sprintf with the variable argument list
specified directly as for vprintf.
swprintf with the variable argument list
specified directly as for vwprintf.
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 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, template);
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 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 argument n specifies the number of elements in the array
argtypes. This is the maximum number of 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 additional 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 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. ISO standard C has
nothing similar.
The function to register a new output conversion is
register_printf_function, declared in `printf.h'.
'Y', it defines the conversion `%Y'.
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. It is advisable not to use lowercase letters,
since the ISO C standard warns that additional lowercase letters may be
standardized in future editions of the standard.
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.
Attention: In the GNU C library versions before 2.0 the
arginfo-function function did not need to be installed unless
the user used the parse_printf_format function. This has 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 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_char
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.
unsigned int wide