]> git.ipfire.org Git - thirdparty/glibc.git/blame - manual/stdio.texi
tests: replace system by xsystem
[thirdparty/glibc.git] / manual / stdio.texi
CommitLineData
28f540f4 1@node I/O on Streams, Low-Level I/O, I/O Overview, Top
34992338 2@c %MENU% High-level, portable I/O facilities
28f540f4 3@chapter Input/Output on Streams
838e5ffe
UD
4@c fix an overfull:
5@tex
6\hyphenation{which-ever}
7@end tex
28f540f4
RM
8
9This chapter describes the functions for creating streams and performing
10input and output operations on them. As discussed in @ref{I/O
11Overview}, a stream is a fairly abstract, high-level concept
12representing a communications channel to a file, device, or process.
13
14@menu
15* Streams:: About the data type representing a stream.
19c3f208 16* Standard Streams:: Streams to the standard input and output
162ba701 17 devices are created for you.
28f540f4
RM
18* Opening Streams:: How to create a stream to talk to a file.
19* Closing Streams:: Close a stream when you are finished with it.
7b4161bb 20* Streams and Threads:: Issues with streams in threaded programs.
b5e73f56 21* Streams and I18N:: Streams in internationalized applications.
28f540f4
RM
22* Simple Output:: Unformatted output by characters and lines.
23* Character Input:: Unformatted input by characters and words.
24* Line Input:: Reading a line or a record from a stream.
25* Unreading:: Peeking ahead/pushing back input just read.
26* Block Input/Output:: Input and output operations on blocks of data.
27* Formatted Output:: @code{printf} and related functions.
28* Customizing Printf:: You can define new conversion specifiers for
162ba701 29 @code{printf} and friends.
28f540f4
RM
30* Formatted Input:: @code{scanf} and related functions.
31* EOF and Errors:: How you can tell if an I/O error happens.
460e040a 32* Error Recovery:: What you can do about errors.
28f540f4 33* Binary Streams:: Some systems distinguish between text files
162ba701 34 and binary files.
28f540f4 35* File Positioning:: About random-access streams.
f65fd747 36* Portable Positioning:: Random access on peculiar ISO C systems.
28f540f4
RM
37* Stream Buffering:: How to control buffering of streams.
38* Other Kinds of Streams:: Streams that do not necessarily correspond
162ba701 39 to an open file.
0501d603 40* Formatted Messages:: Print strictly formatted messages.
28f540f4
RM
41@end menu
42
43@node Streams
44@section Streams
45
46For historical reasons, the type of the C data structure that represents
47a stream is called @code{FILE} rather than ``stream''. Since most of
48the library functions deal with objects of type @code{FILE *}, sometimes
49the term @dfn{file pointer} is also used to mean ``stream''. This leads
50to unfortunate confusion over terminology in many books on C. This
51manual, however, is careful to use the terms ``file'' and ``stream''
52only in the technical sense.
53@cindex file pointer
54
55@pindex stdio.h
56The @code{FILE} type is declared in the header file @file{stdio.h}.
57
28f540f4 58@deftp {Data Type} FILE
d08a7e4c 59@standards{ISO, stdio.h}
28f540f4
RM
60This is the data type used to represent stream objects. A @code{FILE}
61object holds all of the internal state information about the connection
62to the associated file, including such things as the file position
63indicator and buffering information. Each stream also has error and
64end-of-file status indicators that can be tested with the @code{ferror}
65and @code{feof} functions; see @ref{EOF and Errors}.
66@end deftp
67
68@code{FILE} objects are allocated and managed internally by the
69input/output library functions. Don't try to create your own objects of
70type @code{FILE}; let the library do it. Your programs should
71deal only with pointers to these objects (that is, @code{FILE *} values)
72rather than the objects themselves.
6d52618b 73@c !!! should say that FILE's have "No user-serviceable parts inside."
28f540f4
RM
74
75@node Standard Streams
76@section Standard Streams
77@cindex standard streams
78@cindex streams, standard
79
80When the @code{main} function of your program is invoked, it already has
81three predefined streams open and available for use. These represent
82the ``standard'' input and output channels that have been established
83for the process.
84
85These streams are declared in the header file @file{stdio.h}.
86@pindex stdio.h
87
28f540f4 88@deftypevar {FILE *} stdin
d08a7e4c 89@standards{ISO, stdio.h}
28f540f4
RM
90The @dfn{standard input} stream, which is the normal source of input for the
91program.
92@end deftypevar
93@cindex standard input stream
94
28f540f4 95@deftypevar {FILE *} stdout
d08a7e4c 96@standards{ISO, stdio.h}
28f540f4
RM
97The @dfn{standard output} stream, which is used for normal output from
98the program.
99@end deftypevar
100@cindex standard output stream
101
28f540f4 102@deftypevar {FILE *} stderr
d08a7e4c 103@standards{ISO, stdio.h}
28f540f4
RM
104The @dfn{standard error} stream, which is used for error messages and
105diagnostics issued by the program.
106@end deftypevar
107@cindex standard error stream
108
a7a93d50 109On @gnusystems{}, you can specify what files or processes correspond to
28f540f4
RM
110these streams using the pipe and redirection facilities provided by the
111shell. (The primitives shells use to implement these facilities are
112described in @ref{File System Interface}.) Most other operating systems
113provide similar mechanisms, but the details of how to use them can vary.
114
1f77f049 115In @theglibc{}, @code{stdin}, @code{stdout}, and @code{stderr} are
b5e73f56
UD
116normal variables which you can set just like any others. For example,
117to redirect the standard output to a file, you could do:
28f540f4
RM
118
119@smallexample
120fclose (stdout);
121stdout = fopen ("standard-output-file", "w");
122@end smallexample
123
124Note however, that in other systems @code{stdin}, @code{stdout}, and
125@code{stderr} are macros that you cannot assign to in the normal way.
126But you can use @code{freopen} to get the effect of closing one and
127reopening it. @xref{Opening Streams}.
128
b5e73f56
UD
129The three streams @code{stdin}, @code{stdout}, and @code{stderr} are not
130unoriented at program start (@pxref{Streams and I18N}).
131
28f540f4
RM
132@node Opening Streams
133@section Opening Streams
134
135@cindex opening a stream
136Opening a file with the @code{fopen} function creates a new stream and
137establishes a connection between the stream and a file. This may
19c3f208 138involve creating a new file.
28f540f4
RM
139
140@pindex stdio.h
141Everything described in this section is declared in the header file
142@file{stdio.h}.
143
28f540f4 144@deftypefun {FILE *} fopen (const char *@var{filename}, const char *@var{opentype})
d08a7e4c 145@standards{ISO, stdio.h}
171e9210
AO
146@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
147@c fopen may leak the list lock if cancelled within _IO_link_in.
28f540f4
RM
148The @code{fopen} function opens a stream for I/O to the file
149@var{filename}, and returns a pointer to the stream.
150
151The @var{opentype} argument is a string that controls how the file is
152opened and specifies attributes of the resulting stream. It must begin
153with one of the following sequences of characters:
154
155@table @samp
156@item r
157Open an existing file for reading only.
158
159@item w
160Open the file for writing only. If the file already exists, it is
161truncated to zero length. Otherwise a new file is created.
162
163@item a
164Open a file for append access; that is, writing at the end of file only.
165If the file already exists, its initial contents are unchanged and
166output to the stream is appended to the end of the file.
167Otherwise, a new, empty file is created.
168
169@item r+
170Open an existing file for both reading and writing. The initial contents
171of the file are unchanged and the initial file position is at the
172beginning of the file.
173
174@item w+
175Open a file for both reading and writing. If the file already exists, it
176is truncated to zero length. Otherwise, a new file is created.
177
178@item a+
179Open or create file for both reading and appending. If the file exists,
180its initial contents are unchanged. Otherwise, a new file is created.
181The initial file position for reading is at the beginning of the file,
182but output is always appended to the end of the file.
183@end table
184
185As you can see, @samp{+} requests a stream that can do both input and
162ba701
PIM
186output. When using such a stream, you must call @code{fflush}
187(@pxref{Stream Buffering}) or a file positioning function such as
188@code{fseek} (@pxref{File Positioning}) when switching from reading
189to writing or vice versa. Otherwise, internal buffers might not be
190emptied properly.
28f540f4
RM
191
192Additional characters may appear after these to specify flags for the
193call. Always put the mode (@samp{r}, @samp{w+}, etc.) first; that is
194the only part you are guaranteed will be understood by all systems.
195
823fbbb4
AJ
196@Theglibc{} defines additional characters for use in @var{opentype}:
197
198@table @samp
199@item c
200The file is opened with cancellation in the I/O functions disabled.
201
202@item e
203The underlying file descriptor will be closed if you use any of the
204@code{exec@dots{}} functions (@pxref{Executing a File}). (This is
205equivalent to having set @code{FD_CLOEXEC} on that descriptor.
206@xref{Descriptor Flags}.)
207
208@item m
209The file is opened and accessed using @code{mmap}. This is only
210supported with files opened for reading.
211
212@item x
213Insist on creating a new file---if a file @var{filename} already
214exists, @code{fopen} fails rather than opening it. If you use
215@samp{x} you are guaranteed that you will not clobber an existing
216file. This is equivalent to the @code{O_EXCL} option to the
217@code{open} function (@pxref{Opening and Closing Files}).
218
ef4e158c
PE
219The @samp{x} modifier is part of @w{ISO C11}, which says the file is
220created with exclusive access; in @theglibc{} this means the
221equivalent of @code{O_EXCL}.
823fbbb4 222@end table
28f540f4
RM
223
224The character @samp{b} in @var{opentype} has a standard meaning; it
225requests a binary stream rather than a text stream. But this makes no
a7a93d50 226difference in POSIX systems (including @gnusystems{}). If both
28f540f4
RM
227@samp{+} and @samp{b} are specified, they can appear in either order.
228@xref{Binary Streams}.
229
4e2e9999
UD
230@cindex stream orientation
231@cindex orientation, stream
232If the @var{opentype} string contains the sequence
233@code{,ccs=@var{STRING}} then @var{STRING} is taken as the name of a
234coded character set and @code{fopen} will mark the stream as
5b23062f
JM
235wide-oriented with appropriate conversion functions in place to convert
236from and to the character set @var{STRING}. Any other stream
4e2e9999
UD
237is opened initially unoriented and the orientation is decided with the
238first file operation. If the first operation is a wide character
239operation, the stream is not only marked as wide-oriented, also the
240conversion functions to convert to the coded character set used for the
241current locale are loaded. This will not change anymore from this point
242on even if the locale selected for the @code{LC_CTYPE} category is
243changed.
244
28f540f4
RM
245Any other characters in @var{opentype} are simply ignored. They may be
246meaningful in other systems.
247
248If the open fails, @code{fopen} returns a null pointer.
a3a4a74e 249
c703cd7a 250When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 25132 bit machine this function is in fact @code{fopen64} since the LFS
a3a4a74e 252interface replaces transparently the old interface.
28f540f4
RM
253@end deftypefun
254
255You can have multiple streams (or file descriptors) pointing to the same
256file open at the same time. If you do only input, this works
257straightforwardly, but you must be careful if any output streams are
258included. @xref{Stream/Descriptor Precautions}. This is equally true
259whether the streams are in one program (not usual) or in several
260programs (which can easily happen). It may be advantageous to use the
261file locking facilities to avoid simultaneous access. @xref{File
262Locks}.
263
a3a4a74e 264@deftypefun {FILE *} fopen64 (const char *@var{filename}, const char *@var{opentype})
d08a7e4c 265@standards{Unix98, stdio.h}
171e9210 266@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @acsfd{} @aculock{}}}
a3a4a74e
UD
267This function is similar to @code{fopen} but the stream it returns a
268pointer for is opened using @code{open64}. Therefore this stream can be
9ceeb279 269used even on files larger than @twoexp{31} bytes on 32 bit machines.
a3a4a74e
UD
270
271Please note that the return type is still @code{FILE *}. There is no
272special @code{FILE} type for the LFS interface.
273
274If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
275bits machine this function is available under the name @code{fopen}
276and so transparently replaces the old interface.
277@end deftypefun
278
28f540f4 279@deftypevr Macro int FOPEN_MAX
d08a7e4c 280@standards{ISO, stdio.h}
28f540f4
RM
281The value of this macro is an integer constant expression that
282represents the minimum number of streams that the implementation
283guarantees can be open simultaneously. You might be able to open more
284than this many streams, but that is not guaranteed. The value of this
285constant is at least eight, which includes the three standard streams
286@code{stdin}, @code{stdout}, and @code{stderr}. In POSIX.1 systems this
287value is determined by the @code{OPEN_MAX} parameter; @pxref{General
288Limits}. In BSD and GNU, it is controlled by the @code{RLIMIT_NOFILE}
289resource limit; @pxref{Limits on Resources}.
290@end deftypevr
291
28f540f4 292@deftypefun {FILE *} freopen (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
d08a7e4c 293@standards{ISO, stdio.h}
171e9210
AO
294@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @acsfd{}}}
295@c Like most I/O operations, this one is guarded by a recursive lock,
296@c released even upon cancellation, but cancellation may leak file
297@c descriptors and leave the stream in an inconsistent state (e.g.,
298@c still bound to the closed descriptor). Also, if the stream is
299@c part-way through a significant update (say running freopen) when a
300@c signal handler calls freopen again on the same stream, the result is
301@c likely to be an inconsistent stream, and the possibility of closing
302@c twice file descriptor number that the stream used to use, the second
303@c time when it might have already been reused by another thread.
28f540f4
RM
304This function is like a combination of @code{fclose} and @code{fopen}.
305It first closes the stream referred to by @var{stream}, ignoring any
306errors that are detected in the process. (Because errors are ignored,
307you should not use @code{freopen} on an output stream if you have
308actually done any output using the stream.) Then the file named by
309@var{filename} is opened with mode @var{opentype} as for @code{fopen},
310and associated with the same stream object @var{stream}.
311
312If the operation fails, a null pointer is returned; otherwise,
f1a67a2c
AZ
313@code{freopen} returns @var{stream}. On Linux, @code{freopen} may also
314fail and set @code{errno} to @code{EBUSY} when the kernel structure for
315the old file descriptor was not initialized completely before @code{freopen}
316was called. This can only happen in multi-threaded programs, when two
317threads race to allocate the same file descriptor number. To avoid the
318possibility of this race, do not use @code{close} to close the underlying
319file descriptor for a @code{FILE}; either use @code{freopen} while the
320file is still open, or use @code{open} and then @code{dup2} to install
321the new file descriptor.
28f540f4
RM
322
323@code{freopen} has traditionally been used to connect a standard stream
324such as @code{stdin} with a file of your own choice. This is useful in
325programs in which use of a standard stream for certain purposes is
1f77f049 326hard-coded. In @theglibc{}, you can simply close the standard
28f540f4
RM
327streams and open new ones with @code{fopen}. But other systems lack
328this ability, so using @code{freopen} is more portable.
a3a4a74e 329
c703cd7a 330When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 33132 bit machine this function is in fact @code{freopen64} since the LFS
a3a4a74e
UD
332interface replaces transparently the old interface.
333@end deftypefun
334
a3a4a74e 335@deftypefun {FILE *} freopen64 (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
d08a7e4c 336@standards{Unix98, stdio.h}
171e9210 337@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @acsfd{}}}
a3a4a74e 338This function is similar to @code{freopen}. The only difference is that
0be8752b 339on 32 bit machine the stream returned is able to read beyond the
9ceeb279 340@twoexp{31} bytes limits imposed by the normal interface. It should be
a3a4a74e
UD
341noted that the stream pointed to by @var{stream} need not be opened
342using @code{fopen64} or @code{freopen64} since its mode is not important
343for this function.
344
345If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
346bits machine this function is available under the name @code{freopen}
347and so transparently replaces the old interface.
28f540f4
RM
348@end deftypefun
349
f8b23b32
UD
350In some situations it is useful to know whether a given stream is
351available for reading or writing. This information is normally not
352available and would have to be remembered separately. Solaris
353introduced a few functions to get this information from the stream
1f77f049 354descriptor and these functions are also available in @theglibc{}.
f8b23b32 355
f8b23b32 356@deftypefun int __freadable (FILE *@var{stream})
d08a7e4c 357@standards{GNU, stdio_ext.h}
171e9210 358@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
f8b23b32
UD
359The @code{__freadable} function determines whether the stream
360@var{stream} was opened to allow reading. In this case the return value
361is nonzero. For write-only streams the function returns zero.
362
363This function is declared in @file{stdio_ext.h}.
364@end deftypefun
365
f8b23b32 366@deftypefun int __fwritable (FILE *@var{stream})
d08a7e4c 367@standards{GNU, stdio_ext.h}
171e9210 368@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
f8b23b32
UD
369The @code{__fwritable} function determines whether the stream
370@var{stream} was opened to allow writing. In this case the return value
371is nonzero. For read-only streams the function returns zero.
372
373This function is declared in @file{stdio_ext.h}.
374@end deftypefun
375
c703cd7a 376For slightly different kinds of problems there are two more functions.
f8b23b32
UD
377They provide even finer-grained information.
378
f8b23b32 379@deftypefun int __freading (FILE *@var{stream})
d08a7e4c 380@standards{GNU, stdio_ext.h}
171e9210 381@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
f8b23b32
UD
382The @code{__freading} function determines whether the stream
383@var{stream} was last read from or whether it is opened read-only. In
384this case the return value is nonzero, otherwise it is zero.
385Determining whether a stream opened for reading and writing was last
386used for writing allows to draw conclusions about the content about the
387buffer, among other things.
388
389This function is declared in @file{stdio_ext.h}.
390@end deftypefun
391
f8b23b32 392@deftypefun int __fwriting (FILE *@var{stream})
d08a7e4c 393@standards{GNU, stdio_ext.h}
171e9210 394@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
f8b23b32
UD
395The @code{__fwriting} function determines whether the stream
396@var{stream} was last written to or whether it is opened write-only. In
397this case the return value is nonzero, otherwise it is zero.
398
399This function is declared in @file{stdio_ext.h}.
400@end deftypefun
401
28f540f4
RM
402
403@node Closing Streams
404@section Closing Streams
405
406@cindex closing a stream
407When a stream is closed with @code{fclose}, the connection between the
0bc93a2f 408stream and the file is canceled. After you have closed a stream, you
28f540f4
RM
409cannot perform any additional operations on it.
410
28f540f4 411@deftypefun int fclose (FILE *@var{stream})
d08a7e4c 412@standards{ISO, stdio.h}
171e9210
AO
413@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{} @acsfd{}}}
414@c After fclose, it is undefined behavior to use the stream it points
415@c to. Therefore, one must only call fclose when the stream is
416@c otherwise unused. Concurrent uses started before will complete
417@c successfully because of the lock, which makes it MT-Safe. Calling it
418@c from a signal handler is perfectly safe if the stream is known to be
419@c no longer used, which is a precondition for fclose to be safe in the
420@c first place; since this is no further requirement, fclose is safe for
421@c use in async signals too. After calling fclose, you can no longer
422@c use the stream, not even to fclose it again, so its memory and file
423@c descriptor may leak if fclose is canceled before @c releasing them.
424@c That the stream must be unused and it becomes unused after the call
425@c is what would enable fclose to be AS- and AC-Safe while freopen
426@c isn't. However, because of the possibility of leaving __gconv_lock
427@c taken upon cancellation, AC-Safety is lost.
28f540f4
RM
428This function causes @var{stream} to be closed and the connection to
429the corresponding file to be broken. Any buffered output is written
430and any buffered input is discarded. The @code{fclose} function returns
431a value of @code{0} if the file was closed successfully, and @code{EOF}
19c3f208 432if an error was detected.
28f540f4
RM
433
434It is important to check for errors when you call @code{fclose} to close
435an output stream, because real, everyday errors can be detected at this
436time. For example, when @code{fclose} writes the remaining buffered
437output, it might get an error because the disk is full. Even if you
438know the buffer is empty, errors can still occur when closing a file if
439you are using NFS.
440
441The function @code{fclose} is declared in @file{stdio.h}.
442@end deftypefun
443
1f77f049 444To close all streams currently available @theglibc{} provides
6bc31da0
UD
445another function.
446
6bc31da0 447@deftypefun int fcloseall (void)
d08a7e4c 448@standards{GNU, stdio.h}
171e9210
AO
449@safety{@prelim{}@mtunsafe{@mtasurace{:streams}}@asunsafe{}@acsafe{}}
450@c Like fclose, using any previously-opened streams after fcloseall is
451@c undefined. However, the implementation of fcloseall isn't equivalent
452@c to calling fclose for all streams: it just flushes and unbuffers all
453@c streams, without any locking. It's the flushing without locking that
454@c makes it unsafe.
6bc31da0 455This function causes all open streams of the process to be closed and
c703cd7a 456the connections to corresponding files to be broken. All buffered data
f2ea0f5b 457is written and any buffered input is discarded. The @code{fcloseall}
6bc31da0
UD
458function returns a value of @code{0} if all the files were closed
459successfully, and @code{EOF} if an error was detected.
460
0be8752b 461This function should be used only in special situations, e.g., when an
6bc31da0 462error occurred and the program must be aborted. Normally each single
0be8752b
UD
463stream should be closed separately so that problems with individual
464streams can be identified. It is also problematic since the standard
465streams (@pxref{Standard Streams}) will also be closed.
6bc31da0
UD
466
467The function @code{fcloseall} is declared in @file{stdio.h}.
468@end deftypefun
469
28f540f4
RM
470If the @code{main} function to your program returns, or if you call the
471@code{exit} function (@pxref{Normal Termination}), all open streams are
472automatically closed properly. If your program terminates in any other
473manner, such as by calling the @code{abort} function (@pxref{Aborting a
474Program}) or from a fatal signal (@pxref{Signal Handling}), open streams
475might not be closed properly. Buffered output might not be flushed and
476files may be incomplete. For more information on buffering of streams,
477see @ref{Stream Buffering}.
478
7b4161bb
UD
479@node Streams and Threads
480@section Streams and Threads
481
482@cindex threads
483@cindex multi-threaded application
484Streams can be used in multi-threaded applications in the same way they
485are used in single-threaded applications. But the programmer must be
11bf311e 486aware of the possible complications. It is important to know about
7b4161bb 487these also if the program one writes never use threads since the design
c703cd7a 488and implementation of many stream functions are heavily influenced by the
f6af7428 489requirements added by multi-threaded programming.
7b4161bb
UD
490
491The POSIX standard requires that by default the stream operations are
0bc93a2f 492atomic. I.e., issuing two stream operations for the same stream in two
7b4161bb
UD
493threads at the same time will cause the operations to be executed as if
494they were issued sequentially. The buffer operations performed while
495reading or writing are protected from other uses of the same stream. To
496do this each stream has an internal lock object which has to be
497(implicitly) acquired before any work can be done.
498
499But there are situations where this is not enough and there are also
500situations where this is not wanted. The implicit locking is not enough
501if the program requires more than one stream function call to happen
502atomically. One example would be if an output line a program wants to
503generate is created by several function calls. The functions by
504themselves would ensure only atomicity of their own operation, but not
505atomicity over all the function calls. For this it is necessary to
506perform the stream locking in the application code.
507
7b4161bb 508@deftypefun void flockfile (FILE *@var{stream})
d08a7e4c 509@standards{POSIX, stdio.h}
171e9210
AO
510@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
511@c There's no way to tell whether the lock was acquired before or after
512@c cancellation so as to unlock only when appropriate.
7b4161bb 513The @code{flockfile} function acquires the internal locking object
f6af7428 514associated with the stream @var{stream}. This ensures that no other
7b4161bb 515thread can explicitly through @code{flockfile}/@code{ftrylockfile} or
c703cd7a 516implicitly through the call of a stream function lock the stream. The
7b4161bb
UD
517thread will block until the lock is acquired. An explicit call to
518@code{funlockfile} has to be used to release the lock.
519@end deftypefun
520
7b4161bb 521@deftypefun int ftrylockfile (FILE *@var{stream})
d08a7e4c 522@standards{POSIX, stdio.h}
171e9210 523@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
f6af7428 524The @code{ftrylockfile} function tries to acquire the internal locking
7b4161bb
UD
525object associated with the stream @var{stream} just like
526@code{flockfile}. But unlike @code{flockfile} this function does not
527block if the lock is not available. @code{ftrylockfile} returns zero if
528the lock was successfully acquired. Otherwise the stream is locked by
529another thread.
530@end deftypefun
531
7b4161bb 532@deftypefun void funlockfile (FILE *@var{stream})
d08a7e4c 533@standards{POSIX, stdio.h}
171e9210 534@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
7b4161bb 535The @code{funlockfile} function releases the internal locking object of
cf822e3c 536the stream @var{stream}. The stream must have been locked before by a
7b4161bb
UD
537call to @code{flockfile} or a successful call of @code{ftrylockfile}.
538The implicit locking performed by the stream operations do not count.
539The @code{funlockfile} function does not return an error status and the
540behavior of a call for a stream which is not locked by the current
541thread is undefined.
542@end deftypefun
543
544The following example shows how the functions above can be used to
545generate an output line atomically even in multi-threaded applications
546(yes, the same job could be done with one @code{fprintf} call but it is
547sometimes not possible):
548
549@smallexample
550FILE *fp;
551@{
95fdc6a0 552 @dots{}
7b4161bb
UD
553 flockfile (fp);
554 fputs ("This is test number ", fp);
555 fprintf (fp, "%d\n", test);
556 funlockfile (fp)
557@}
558@end smallexample
559
560Without the explicit locking it would be possible for another thread to
c703cd7a 561use the stream @var{fp} after the @code{fputs} call returns and before
7b4161bb
UD
562@code{fprintf} was called with the result that the number does not
563follow the word @samp{number}.
564
565From this description it might already be clear that the locking objects
566in streams are no simple mutexes. Since locking the same stream twice
567in the same thread is allowed the locking objects must be equivalent to
568recursive mutexes. These mutexes keep track of the owner and the number
569of times the lock is acquired. The same number of @code{funlockfile}
570calls by the same threads is necessary to unlock the stream completely.
571For instance:
572
573@smallexample
574void
575foo (FILE *fp)
576@{
577 ftrylockfile (fp);
578 fputs ("in foo\n", fp);
579 /* @r{This is very wrong!!!} */
580 funlockfile (fp);
581@}
582@end smallexample
583
584It is important here that the @code{funlockfile} function is only called
585if the @code{ftrylockfile} function succeeded in locking the stream. It
586is therefore always wrong to ignore the result of @code{ftrylockfile}.
587And it makes no sense since otherwise one would use @code{flockfile}.
588The result of code like that above is that either @code{funlockfile}
f6af7428 589tries to free a stream that hasn't been locked by the current thread or it
7b4161bb
UD
590frees the stream prematurely. The code should look like this:
591
592@smallexample
593void
594foo (FILE *fp)
595@{
596 if (ftrylockfile (fp) == 0)
597 @{
598 fputs ("in foo\n", fp);
599 funlockfile (fp);
600 @}
601@}
602@end smallexample
603
c703cd7a 604Now that we covered why it is necessary to have locking it is
f6af7428 605necessary to talk about situations when locking is unwanted and what can
7b4161bb
UD
606be done. The locking operations (explicit or implicit) don't come for
607free. Even if a lock is not taken the cost is not zero. The operations
3ca9e670 608which have to be performed require memory operations that are safe in
7b4161bb
UD
609multi-processor environments. With the many local caches involved in
610such systems this is quite costly. So it is best to avoid the locking
3ca9e670
UD
611completely if it is not needed -- because the code in question is never
612used in a context where two or more threads may use a stream at a time.
7b4161bb
UD
613This can be determined most of the time for application code; for
614library code which can be used in many contexts one should default to be
615conservative and use locking.
616
617There are two basic mechanisms to avoid locking. The first is to use
618the @code{_unlocked} variants of the stream operations. The POSIX
1f77f049 619standard defines quite a few of those and @theglibc{} adds a few
7b4161bb 620more. These variants of the functions behave just like the functions
3ca9e670 621with the name without the suffix except that they do not lock the
7b4161bb 622stream. Using these functions is very desirable since they are
f6af7428 623potentially much faster. This is not only because the locking
7b4161bb 624operation itself is avoided. More importantly, functions like
0bc93a2f 625@code{putc} and @code{getc} are very simple and traditionally (before the
7b4161bb 626introduction of threads) were implemented as macros which are very fast
3ca9e670
UD
627if the buffer is not empty. With the addition of locking requirements
628these functions are no longer implemented as macros since they would
bbf70ae9 629expand to too much code.
3ca9e670 630But these macros are still available with the same functionality under the new
7b4161bb
UD
631names @code{putc_unlocked} and @code{getc_unlocked}. This possibly huge
632difference of speed also suggests the use of the @code{_unlocked}
633functions even if locking is required. The difference is that the
634locking then has to be performed in the program:
635
636@smallexample
637void
638foo (FILE *fp, char *buf)
639@{
640 flockfile (fp);
641 while (*buf != '/')
642 putc_unlocked (*buf++, fp);
643 funlockfile (fp);
644@}
645@end smallexample
646
647If in this example the @code{putc} function would be used and the
648explicit locking would be missing the @code{putc} function would have to
649acquire the lock in every call, potentially many times depending on when
650the loop terminates. Writing it the way illustrated above allows the
651@code{putc_unlocked} macro to be used which means no locking and direct
652manipulation of the buffer of the stream.
653
654A second way to avoid locking is by using a non-standard function which
1f77f049 655was introduced in Solaris and is available in @theglibc{} as well.
7b4161bb 656
7b4161bb 657@deftypefun int __fsetlocking (FILE *@var{stream}, int @var{type})
d08a7e4c 658@standards{GNU, stdio_ext.h}
171e9210
AO
659@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asulock{}}@acsafe{}}
660@c Changing the implicit-locking status of a stream while it's in use by
661@c another thread may cause a lock to be implicitly acquired and not
662@c released, or vice-versa. This function should probably hold the lock
663@c while changing this setting, to make sure we don't change it while
664@c there are any concurrent uses. Meanwhile, callers should acquire the
665@c lock themselves to be safe, and even concurrent uses with external
666@c locking will be fine, as long as functions that require external
667@c locking are not called without holding locks.
7b4161bb
UD
668
669The @code{__fsetlocking} function can be used to select whether the
670stream operations will implicitly acquire the locking object of the
671stream @var{stream}. By default this is done but it can be disabled and
672reinstated using this function. There are three values defined for the
673@var{type} parameter.
674
675@vtable @code
676@item FSETLOCKING_INTERNAL
677The stream @code{stream} will from now on use the default internal
678locking. Every stream operation with exception of the @code{_unlocked}
679variants will implicitly lock the stream.
680
681@item FSETLOCKING_BYCALLER
c703cd7a 682After the @code{__fsetlocking} function returns, the user is responsible
7b4161bb
UD
683for locking the stream. None of the stream operations will implicitly
684do this anymore until the state is set back to
685@code{FSETLOCKING_INTERNAL}.
686
687@item FSETLOCKING_QUERY
688@code{__fsetlocking} only queries the current locking state of the
689stream. The return value will be @code{FSETLOCKING_INTERNAL} or
690@code{FSETLOCKING_BYCALLER} depending on the state.
691@end vtable
692
693The return value of @code{__fsetlocking} is either
694@code{FSETLOCKING_INTERNAL} or @code{FSETLOCKING_BYCALLER} depending on
695the state of the stream before the call.
696
697This function and the values for the @var{type} parameter are declared
698in @file{stdio_ext.h}.
699@end deftypefun
700
701This function is especially useful when program code has to be used
702which is written without knowledge about the @code{_unlocked} functions
3ca9e670 703(or if the programmer was too lazy to use them).
7b4161bb 704
b5e73f56
UD
705@node Streams and I18N
706@section Streams in Internationalized Applications
707
708@w{ISO C90} introduced the new type @code{wchar_t} to allow handling
709larger character sets. What was missing was a possibility to output
710strings of @code{wchar_t} directly. One had to convert them into
711multibyte strings using @code{mbstowcs} (there was no @code{mbsrtowcs}
712yet) and then use the normal stream functions. While this is doable it
713is very cumbersome since performing the conversions is not trivial and
714greatly increases program complexity and size.
715
716The Unix standard early on (I think in XPG4.2) introduced two additional
717format specifiers for the @code{printf} and @code{scanf} families of
718functions. Printing and reading of single wide characters was made
719possible using the @code{%C} specifier and wide character strings can be
720handled with @code{%S}. These modifiers behave just like @code{%c} and
721@code{%s} only that they expect the corresponding argument to have the
722wide character type and that the wide character and string are
723transformed into/from multibyte strings before being used.
724
725This was a beginning but it is still not good enough. Not always is it
726desirable to use @code{printf} and @code{scanf}. The other, smaller and
727faster functions cannot handle wide characters. Second, it is not
728possible to have a format string for @code{printf} and @code{scanf}
729consisting of wide characters. The result is that format strings would
730have to be generated if they have to contain non-basic characters.
731
732@cindex C++ streams
733@cindex streams, C++
734In the @w{Amendment 1} to @w{ISO C90} a whole new set of functions was
735added to solve the problem. Most of the stream functions got a
736counterpart which take a wide character or wide character string instead
737of a character or string respectively. The new functions operate on the
738same streams (like @code{stdout}). This is different from the model of
739the C++ runtime library where separate streams for wide and normal I/O
740are used.
741
742@cindex orientation, stream
743@cindex stream orientation
744Being able to use the same stream for wide and normal operations comes
745with a restriction: a stream can be used either for wide operations or
746for normal operations. Once it is decided there is no way back. Only a
747call to @code{freopen} or @code{freopen64} can reset the
748@dfn{orientation}. The orientation can be decided in three ways:
749
750@itemize @bullet
751@item
c703cd7a 752If any of the normal character functions are used (this includes the
22298d18 753@code{fread} and @code{fwrite} functions) the stream is marked as not
b5e73f56
UD
754wide oriented.
755
756@item
c703cd7a 757If any of the wide character functions are used the stream is marked as
22298d18 758wide oriented.
b5e73f56
UD
759
760@item
761The @code{fwide} function can be used to set the orientation either way.
762@end itemize
763
764It is important to never mix the use of wide and not wide operations on
765a stream. There are no diagnostics issued. The application behavior
766will simply be strange or the application will simply crash. The
c703cd7a 767@code{fwide} function can help avoid this.
b5e73f56 768
b5e73f56 769@deftypefun int fwide (FILE *@var{stream}, int @var{mode})
d08a7e4c 770@standards{ISO, wchar.h}
171e9210
AO
771@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{}}}
772@c Querying is always safe, but changing the stream when it's in use
773@c upthread may be problematic. Like most lock-acquiring functions,
774@c this one may leak the lock if canceled.
b5e73f56 775
22298d18 776The @code{fwide} function can be used to set and query the state of the
b5e73f56
UD
777orientation of the stream @var{stream}. If the @var{mode} parameter has
778a positive value the streams get wide oriented, for negative values
779narrow oriented. It is not possible to overwrite previous orientations
780with @code{fwide}. I.e., if the stream @var{stream} was already
781oriented before the call nothing is done.
782
783If @var{mode} is zero the current orientation state is queried and
784nothing is changed.
785
786The @code{fwide} function returns a negative value, zero, or a positive
787value if the stream is narrow, not at all, or wide oriented
788respectively.
789
790This function was introduced in @w{Amendment 1} to @w{ISO C90} and is
791declared in @file{wchar.h}.
792@end deftypefun
793
794It is generally a good idea to orient a stream as early as possible.
795This can prevent surprise especially for the standard streams
796@code{stdin}, @code{stdout}, and @code{stderr}. If some library
797function in some situations uses one of these streams and this use
798orients the stream in a different way the rest of the application
799expects it one might end up with hard to reproduce errors. Remember
800that no errors are signal if the streams are used incorrectly. Leaving
801a stream unoriented after creation is normally only necessary for
802library functions which create streams which can be used in different
803contexts.
804
805When writing code which uses streams and which can be used in different
806contexts it is important to query the orientation of the stream before
807using it (unless the rules of the library interface demand a specific
808orientation). The following little, silly function illustrates this.
809
810@smallexample
811void
812print_f (FILE *fp)
813@{
814 if (fwide (fp, 0) > 0)
815 /* @r{Positive return value means wide orientation.} */
816 fputwc (L'f', fp);
817 else
818 fputc ('f', fp);
819@}
820@end smallexample
821
822Note that in this case the function @code{print_f} decides about the
823orientation of the stream if it was unoriented before (will not happen
c703cd7a 824if the advice above is followed).
b5e73f56
UD
825
826The encoding used for the @code{wchar_t} values is unspecified and the
827user must not make any assumptions about it. For I/O of @code{wchar_t}
828values this means that it is impossible to write these values directly
829to the stream. This is not what follows from the @w{ISO C} locale model
830either. What happens instead is that the bytes read from or written to
831the underlying media are first converted into the internal encoding
832chosen by the implementation for @code{wchar_t}. The external encoding
833is determined by the @code{LC_CTYPE} category of the current locale or
834by the @samp{ccs} part of the mode specification given to @code{fopen},
835@code{fopen64}, @code{freopen}, or @code{freopen64}. How and when the
c703cd7a 836conversion happens is unspecified and it happens invisibly to the user.
b5e73f56
UD
837
838Since a stream is created in the unoriented state it has at that point
839no conversion associated with it. The conversion which will be used is
840determined by the @code{LC_CTYPE} category selected at the time the
841stream is oriented. If the locales are changed at the runtime this
842might produce surprising results unless one pays attention. This is
843just another good reason to orient the stream explicitly as soon as
844possible, perhaps with a call to @code{fwide}.
845
28f540f4
RM
846@node Simple Output
847@section Simple Output by Characters or Lines
848
849@cindex writing to a stream, by characters
850This section describes functions for performing character- and
851line-oriented output.
852
c703cd7a 853These narrow stream functions are declared in the header file
b5e73f56 854@file{stdio.h} and the wide stream functions in @file{wchar.h}.
28f540f4 855@pindex stdio.h
b5e73f56 856@pindex wchar.h
28f540f4 857
28f540f4 858@deftypefun int fputc (int @var{c}, FILE *@var{stream})
d08a7e4c 859@standards{ISO, stdio.h}
171e9210
AO
860@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
861@c If the stream is in use when interrupted by a signal, the recursive
862@c lock won't help ensure the stream is consistent; indeed, if fputc
863@c gets a signal precisely before the post-incremented _IO_write_ptr
864@c value is stored, we may overwrite the interrupted write. Conversely,
865@c depending on compiler optimizations, the incremented _IO_write_ptr
866@c may be stored before the character is stored in the buffer,
867@c corrupting the stream if async cancel hits between the two stores.
868@c There may be other reasons for AS- and AC-unsafety in the overflow
869@c cases.
28f540f4 870The @code{fputc} function converts the character @var{c} to type
19c3f208 871@code{unsigned char}, and writes it to the stream @var{stream}.
28f540f4
RM
872@code{EOF} is returned if a write error occurs; otherwise the
873character @var{c} is returned.
874@end deftypefun
875
b5e73f56 876@deftypefun wint_t fputwc (wchar_t @var{wc}, FILE *@var{stream})
d08a7e4c 877@standards{ISO, wchar.h}
171e9210 878@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
b5e73f56
UD
879The @code{fputwc} function writes the wide character @var{wc} to the
880stream @var{stream}. @code{WEOF} is returned if a write error occurs;
881otherwise the character @var{wc} is returned.
882@end deftypefun
883
7b4161bb 884@deftypefun int fputc_unlocked (int @var{c}, FILE *@var{stream})
d08a7e4c 885@standards{POSIX, stdio.h}
171e9210
AO
886@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
887@c The unlocked functions can't possibly satisfy the MT-Safety
888@c requirements on their own, because they require external locking for
889@c safety.
7b4161bb 890The @code{fputc_unlocked} function is equivalent to the @code{fputc}
1dc843f7 891function except that it does not implicitly lock the stream.
7b4161bb
UD
892@end deftypefun
893
8ded91fb 894@deftypefun wint_t fputwc_unlocked (wchar_t @var{wc}, FILE *@var{stream})
d08a7e4c 895@standards{POSIX, wchar.h}
171e9210 896@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 897The @code{fputwc_unlocked} function is equivalent to the @code{fputwc}
1dc843f7 898function except that it does not implicitly lock the stream.
b5e73f56
UD
899
900This function is a GNU extension.
901@end deftypefun
902
28f540f4 903@deftypefun int putc (int @var{c}, FILE *@var{stream})
d08a7e4c 904@standards{ISO, stdio.h}
171e9210 905@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
28f540f4
RM
906This is just like @code{fputc}, except that most systems implement it as
907a macro, making it faster. One consequence is that it may evaluate the
908@var{stream} argument more than once, which is an exception to the
909general rule for macros. @code{putc} is usually the best function to
910use for writing a single character.
911@end deftypefun
912
b5e73f56 913@deftypefun wint_t putwc (wchar_t @var{wc}, FILE *@var{stream})
d08a7e4c 914@standards{ISO, wchar.h}
171e9210 915@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
b5e73f56
UD
916This is just like @code{fputwc}, except that it can be implement as
917a macro, making it faster. One consequence is that it may evaluate the
918@var{stream} argument more than once, which is an exception to the
919general rule for macros. @code{putwc} is usually the best function to
920use for writing a single wide character.
921@end deftypefun
922
7b4161bb 923@deftypefun int putc_unlocked (int @var{c}, FILE *@var{stream})
d08a7e4c 924@standards{POSIX, stdio.h}
171e9210 925@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 926The @code{putc_unlocked} function is equivalent to the @code{putc}
1dc843f7 927function except that it does not implicitly lock the stream.
7b4161bb
UD
928@end deftypefun
929
b5e73f56 930@deftypefun wint_t putwc_unlocked (wchar_t @var{wc}, FILE *@var{stream})
d08a7e4c 931@standards{GNU, wchar.h}
171e9210 932@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 933The @code{putwc_unlocked} function is equivalent to the @code{putwc}
1dc843f7 934function except that it does not implicitly lock the stream.
b5e73f56
UD
935
936This function is a GNU extension.
937@end deftypefun
938
28f540f4 939@deftypefun int putchar (int @var{c})
d08a7e4c 940@standards{ISO, stdio.h}
171e9210 941@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
28f540f4
RM
942The @code{putchar} function is equivalent to @code{putc} with
943@code{stdout} as the value of the @var{stream} argument.
944@end deftypefun
945
c44a663d 946@deftypefun wint_t putwchar (wchar_t @var{wc})
d08a7e4c 947@standards{ISO, wchar.h}
171e9210 948@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
b5e73f56
UD
949The @code{putwchar} function is equivalent to @code{putwc} with
950@code{stdout} as the value of the @var{stream} argument.
951@end deftypefun
952
7b4161bb 953@deftypefun int putchar_unlocked (int @var{c})
d08a7e4c 954@standards{POSIX, stdio.h}
171e9210 955@safety{@prelim{}@mtunsafe{@mtasurace{:stdout}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 956The @code{putchar_unlocked} function is equivalent to the @code{putchar}
1dc843f7 957function except that it does not implicitly lock the stream.
7b4161bb
UD
958@end deftypefun
959
b5e73f56 960@deftypefun wint_t putwchar_unlocked (wchar_t @var{wc})
d08a7e4c 961@standards{GNU, wchar.h}
171e9210 962@safety{@prelim{}@mtunsafe{@mtasurace{:stdout}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 963The @code{putwchar_unlocked} function is equivalent to the @code{putwchar}
1dc843f7 964function except that it does not implicitly lock the stream.
b5e73f56
UD
965
966This function is a GNU extension.
967@end deftypefun
968
28f540f4 969@deftypefun int fputs (const char *@var{s}, FILE *@var{stream})
d08a7e4c 970@standards{ISO, stdio.h}
171e9210 971@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
28f540f4
RM
972The function @code{fputs} writes the string @var{s} to the stream
973@var{stream}. The terminating null character is not written.
974This function does @emph{not} add a newline character, either.
975It outputs only the characters in the string.
976
977This function returns @code{EOF} if a write error occurs, and otherwise
978a non-negative value.
979
980For example:
981
982@smallexample
983fputs ("Are ", stdout);
984fputs ("you ", stdout);
985fputs ("hungry?\n", stdout);
986@end smallexample
987
988@noindent
989outputs the text @samp{Are you hungry?} followed by a newline.
990@end deftypefun
991
b5e73f56 992@deftypefun int fputws (const wchar_t *@var{ws}, FILE *@var{stream})
d08a7e4c 993@standards{ISO, wchar.h}
171e9210 994@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{} @aculock{}}}
b5e73f56
UD
995The function @code{fputws} writes the wide character string @var{ws} to
996the stream @var{stream}. The terminating null character is not written.
997This function does @emph{not} add a newline character, either. It
998outputs only the characters in the string.
999
1000This function returns @code{WEOF} if a write error occurs, and otherwise
1001a non-negative value.
1002@end deftypefun
1003
7b4161bb 1004@deftypefun int fputs_unlocked (const char *@var{s}, FILE *@var{stream})
d08a7e4c 1005@standards{GNU, stdio.h}
171e9210 1006@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1007The @code{fputs_unlocked} function is equivalent to the @code{fputs}
1dc843f7 1008function except that it does not implicitly lock the stream.
7b4161bb
UD
1009
1010This function is a GNU extension.
1011@end deftypefun
1012
b5e73f56 1013@deftypefun int fputws_unlocked (const wchar_t *@var{ws}, FILE *@var{stream})
d08a7e4c 1014@standards{GNU, wchar.h}
171e9210 1015@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 1016The @code{fputws_unlocked} function is equivalent to the @code{fputws}
1dc843f7 1017function except that it does not implicitly lock the stream.
b5e73f56
UD
1018
1019This function is a GNU extension.
1020@end deftypefun
1021
28f540f4 1022@deftypefun int puts (const char *@var{s})
d08a7e4c 1023@standards{ISO, stdio.h}
171e9210 1024@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1025The @code{puts} function writes the string @var{s} to the stream
1026@code{stdout} followed by a newline. The terminating null character of
1027the string is not written. (Note that @code{fputs} does @emph{not}
1028write a newline as this function does.)
1029
1030@code{puts} is the most convenient function for printing simple
1031messages. For example:
1032
1033@smallexample
1034puts ("This is a message.");
1035@end smallexample
0be8752b
UD
1036
1037@noindent
1038outputs the text @samp{This is a message.} followed by a newline.
28f540f4
RM
1039@end deftypefun
1040
28f540f4 1041@deftypefun int putw (int @var{w}, FILE *@var{stream})
d08a7e4c 1042@standards{SVID, stdio.h}
171e9210 1043@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1044This function writes the word @var{w} (that is, an @code{int}) to
1045@var{stream}. It is provided for compatibility with SVID, but we
1046recommend you use @code{fwrite} instead (@pxref{Block Input/Output}).
1047@end deftypefun
1048
1049@node Character Input
1050@section Character Input
1051
1052@cindex reading from a stream, by characters
b5e73f56 1053This section describes functions for performing character-oriented
c703cd7a 1054input. These narrow stream functions are declared in the header file
b5e73f56
UD
1055@file{stdio.h} and the wide character functions are declared in
1056@file{wchar.h}.
28f540f4 1057@pindex stdio.h
b5e73f56
UD
1058@pindex wchar.h
1059
1060These functions return an @code{int} or @code{wint_t} value (for narrow
1061and wide stream functions respectively) that is either a character of
1062input, or the special value @code{EOF}/@code{WEOF} (usually -1). For
1063the narrow stream functions it is important to store the result of these
1064functions in a variable of type @code{int} instead of @code{char}, even
1065when you plan to use it only as a character. Storing @code{EOF} in a
1066@code{char} variable truncates its value to the size of a character, so
1067that it is no longer distinguishable from the valid character
1068@samp{(char) -1}. So always use an @code{int} for the result of
1069@code{getc} and friends, and check for @code{EOF} after the call; once
1070you've verified that the result is not @code{EOF}, you can be sure that
1071it will fit in a @samp{char} variable without loss of information.
28f540f4 1072
28f540f4 1073@deftypefun int fgetc (FILE *@var{stream})
d08a7e4c 1074@standards{ISO, stdio.h}
171e9210
AO
1075@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
1076@c Same caveats as fputc, but instead of losing a write in case of async
1077@c signals, we may read the same character more than once, and the
1078@c stream may be left in odd states due to cancellation in the underflow
1079@c cases.
28f540f4
RM
1080This function reads the next character as an @code{unsigned char} from
1081the stream @var{stream} and returns its value, converted to an
1082@code{int}. If an end-of-file condition or read error occurs,
19c3f208 1083@code{EOF} is returned instead.
28f540f4
RM
1084@end deftypefun
1085
b5e73f56 1086@deftypefun wint_t fgetwc (FILE *@var{stream})
d08a7e4c 1087@standards{ISO, wchar.h}
171e9210 1088@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
b5e73f56
UD
1089This function reads the next wide character from the stream @var{stream}
1090and returns its value. If an end-of-file condition or read error
1091occurs, @code{WEOF} is returned instead.
1092@end deftypefun
1093
7b4161bb 1094@deftypefun int fgetc_unlocked (FILE *@var{stream})
d08a7e4c 1095@standards{POSIX, stdio.h}
171e9210 1096@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1097The @code{fgetc_unlocked} function is equivalent to the @code{fgetc}
1dc843f7 1098function except that it does not implicitly lock the stream.
7b4161bb
UD
1099@end deftypefun
1100
b5e73f56 1101@deftypefun wint_t fgetwc_unlocked (FILE *@var{stream})
d08a7e4c 1102@standards{GNU, wchar.h}
171e9210 1103@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 1104The @code{fgetwc_unlocked} function is equivalent to the @code{fgetwc}
1dc843f7 1105function except that it does not implicitly lock the stream.
b5e73f56
UD
1106
1107This function is a GNU extension.
1108@end deftypefun
1109
28f540f4 1110@deftypefun int getc (FILE *@var{stream})
d08a7e4c 1111@standards{ISO, stdio.h}
171e9210 1112@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1113This is just like @code{fgetc}, except that it is permissible (and
1114typical) for it to be implemented as a macro that evaluates the
1115@var{stream} argument more than once. @code{getc} is often highly
1116optimized, so it is usually the best function to use to read a single
1117character.
1118@end deftypefun
1119
b5e73f56 1120@deftypefun wint_t getwc (FILE *@var{stream})
d08a7e4c 1121@standards{ISO, wchar.h}
171e9210 1122@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
b5e73f56
UD
1123This is just like @code{fgetwc}, except that it is permissible for it to
1124be implemented as a macro that evaluates the @var{stream} argument more
1125than once. @code{getwc} can be highly optimized, so it is usually the
1126best function to use to read a single wide character.
1127@end deftypefun
1128
7b4161bb 1129@deftypefun int getc_unlocked (FILE *@var{stream})
d08a7e4c 1130@standards{POSIX, stdio.h}
171e9210 1131@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1132The @code{getc_unlocked} function is equivalent to the @code{getc}
1dc843f7 1133function except that it does not implicitly lock the stream.
7b4161bb
UD
1134@end deftypefun
1135
b5e73f56 1136@deftypefun wint_t getwc_unlocked (FILE *@var{stream})
d08a7e4c 1137@standards{GNU, wchar.h}
171e9210 1138@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 1139The @code{getwc_unlocked} function is equivalent to the @code{getwc}
1dc843f7 1140function except that it does not implicitly lock the stream.
b5e73f56
UD
1141
1142This function is a GNU extension.
1143@end deftypefun
1144
28f540f4 1145@deftypefun int getchar (void)
d08a7e4c 1146@standards{ISO, stdio.h}
171e9210 1147@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1148The @code{getchar} function is equivalent to @code{getc} with @code{stdin}
1149as the value of the @var{stream} argument.
1150@end deftypefun
1151
b5e73f56 1152@deftypefun wint_t getwchar (void)
d08a7e4c 1153@standards{ISO, wchar.h}
171e9210 1154@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
b5e73f56
UD
1155The @code{getwchar} function is equivalent to @code{getwc} with @code{stdin}
1156as the value of the @var{stream} argument.
1157@end deftypefun
1158
7b4161bb 1159@deftypefun int getchar_unlocked (void)
d08a7e4c 1160@standards{POSIX, stdio.h}
171e9210 1161@safety{@prelim{}@mtunsafe{@mtasurace{:stdin}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1162The @code{getchar_unlocked} function is equivalent to the @code{getchar}
1dc843f7 1163function except that it does not implicitly lock the stream.
7b4161bb
UD
1164@end deftypefun
1165
b5e73f56 1166@deftypefun wint_t getwchar_unlocked (void)
d08a7e4c 1167@standards{GNU, wchar.h}
171e9210 1168@safety{@prelim{}@mtunsafe{@mtasurace{:stdin}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 1169The @code{getwchar_unlocked} function is equivalent to the @code{getwchar}
1dc843f7 1170function except that it does not implicitly lock the stream.
b5e73f56
UD
1171
1172This function is a GNU extension.
1173@end deftypefun
1174
28f540f4
RM
1175Here is an example of a function that does input using @code{fgetc}. It
1176would work just as well using @code{getc} instead, or using
b5e73f56
UD
1177@code{getchar ()} instead of @w{@code{fgetc (stdin)}}. The code would
1178also work the same for the wide character stream functions.
28f540f4
RM
1179
1180@smallexample
1181int
1182y_or_n_p (const char *question)
1183@{
1184 fputs (question, stdout);
1185 while (1)
1186 @{
1187 int c, answer;
1188 /* @r{Write a space to separate answer from question.} */
1189 fputc (' ', stdout);
1190 /* @r{Read the first character of the line.}
162ba701 1191 @r{This should be the answer character, but might not be.} */
28f540f4
RM
1192 c = tolower (fgetc (stdin));
1193 answer = c;
1194 /* @r{Discard rest of input line.} */
1195 while (c != '\n' && c != EOF)
162ba701 1196 c = fgetc (stdin);
28f540f4
RM
1197 /* @r{Obey the answer if it was valid.} */
1198 if (answer == 'y')
162ba701 1199 return 1;
28f540f4 1200 if (answer == 'n')
162ba701 1201 return 0;
28f540f4
RM
1202 /* @r{Answer was invalid: ask for valid answer.} */
1203 fputs ("Please answer y or n:", stdout);
1204 @}
1205@}
1206@end smallexample
1207
28f540f4 1208@deftypefun int getw (FILE *@var{stream})
d08a7e4c 1209@standards{SVID, stdio.h}
171e9210 1210@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1211This function reads a word (that is, an @code{int}) from @var{stream}.
1212It's provided for compatibility with SVID. We recommend you use
1213@code{fread} instead (@pxref{Block Input/Output}). Unlike @code{getc},
1214any @code{int} value could be a valid result. @code{getw} returns
1215@code{EOF} when it encounters end-of-file or an error, but there is no
1216way to distinguish this from an input word with value -1.
1217@end deftypefun
1218
1219@node Line Input
1220@section Line-Oriented Input
1221
b5e73f56 1222Since many programs interpret input on the basis of lines, it is
28f540f4
RM
1223convenient to have functions to read a line of text from a stream.
1224
1225Standard C has functions to do this, but they aren't very safe: null
1226characters and even (for @code{gets}) long lines can confuse them. So
1f77f049 1227@theglibc{} provides the nonstandard @code{getline} function that
28f540f4
RM
1228makes it easy to read lines reliably.
1229
1230Another GNU extension, @code{getdelim}, generalizes @code{getline}. It
1231reads a delimited record, defined as everything through the next
1232occurrence of a specified delimiter character.
1233
1234All these functions are declared in @file{stdio.h}.
1235
28f540f4 1236@deftypefun ssize_t getline (char **@var{lineptr}, size_t *@var{n}, FILE *@var{stream})
d08a7e4c 1237@standards{GNU, stdio.h}
171e9210
AO
1238@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@aculock{} @acucorrupt{} @acsmem{}}}
1239@c Besides the usual possibility of getting an inconsistent stream in a
1240@c signal handler or leaving it inconsistent in case of cancellation,
1241@c the possibility of leaving a dangling pointer upon cancellation
1242@c between reallocing the buffer at *lineptr and updating the pointer
1243@c brings about another case of @acucorrupt.
28f540f4
RM
1244This function reads an entire line from @var{stream}, storing the text
1245(including the newline and a terminating null character) in a buffer
1246and storing the buffer address in @code{*@var{lineptr}}.
1247
1248Before calling @code{getline}, you should place in @code{*@var{lineptr}}
1249the address of a buffer @code{*@var{n}} bytes long, allocated with
1250@code{malloc}. If this buffer is long enough to hold the line,
1251@code{getline} stores the line in this buffer. Otherwise,
1252@code{getline} makes the buffer bigger using @code{realloc}, storing the
1253new buffer address back in @code{*@var{lineptr}} and the increased size
1254back in @code{*@var{n}}.
1255@xref{Unconstrained Allocation}.
1256
1257If you set @code{*@var{lineptr}} to a null pointer, and @code{*@var{n}}
1258to zero, before the call, then @code{getline} allocates the initial
1c21d115
DS
1259buffer for you by calling @code{malloc}. This buffer remains allocated
1260even if @code{getline} encounters errors and is unable to read any bytes.
28f540f4
RM
1261
1262In either case, when @code{getline} returns, @code{*@var{lineptr}} is
1263a @code{char *} which points to the text of the line.
1264
1265When @code{getline} is successful, it returns the number of characters
1266read (including the newline, but not including the terminating null).
1267This value enables you to distinguish null characters that are part of
1268the line from the null character inserted as a terminator.
1269
1270This function is a GNU extension, but it is the recommended way to read
1271lines from a stream. The alternative standard functions are unreliable.
1272
ec28fc7c
UD
1273If an error occurs or end of file is reached without any bytes read,
1274@code{getline} returns @code{-1}.
28f540f4
RM
1275@end deftypefun
1276
28f540f4 1277@deftypefun ssize_t getdelim (char **@var{lineptr}, size_t *@var{n}, int @var{delimiter}, FILE *@var{stream})
d08a7e4c 1278@standards{GNU, stdio.h}
171e9210
AO
1279@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@aculock{} @acucorrupt{} @acsmem{}}}
1280@c See the getline @acucorrupt note.
28f540f4
RM
1281This function is like @code{getline} except that the character which
1282tells it to stop reading is not necessarily newline. The argument
1283@var{delimiter} specifies the delimiter character; @code{getdelim} keeps
1284reading until it sees that character (or end of file).
1285
1286The text is stored in @var{lineptr}, including the delimiter character
1287and a terminating null. Like @code{getline}, @code{getdelim} makes
1288@var{lineptr} bigger if it isn't big enough.
1289
1290@code{getline} is in fact implemented in terms of @code{getdelim}, just
1291like this:
1292
1293@smallexample
1294ssize_t
1295getline (char **lineptr, size_t *n, FILE *stream)
1296@{
1297 return getdelim (lineptr, n, '\n', stream);
1298@}
1299@end smallexample
1300@end deftypefun
1301
28f540f4 1302@deftypefun {char *} fgets (char *@var{s}, int @var{count}, FILE *@var{stream})
d08a7e4c 1303@standards{ISO, stdio.h}
171e9210 1304@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1305The @code{fgets} function reads characters from the stream @var{stream}
1306up to and including a newline character and stores them in the string
1307@var{s}, adding a null character to mark the end of the string. You
1308must supply @var{count} characters worth of space in @var{s}, but the
1309number of characters read is at most @var{count} @minus{} 1. The extra
1310character space is used to hold the null character at the end of the
1311string.
1312
1313If the system is already at end of file when you call @code{fgets}, then
1314the contents of the array @var{s} are unchanged and a null pointer is
1315returned. A null pointer is also returned if a read error occurs.
1316Otherwise, the return value is the pointer @var{s}.
1317
1318@strong{Warning:} If the input data has a null character, you can't tell.
1319So don't use @code{fgets} unless you know the data cannot contain a null.
1320Don't use it to read files edited by the user because, if the user inserts
1321a null character, you should either handle it properly or print a clear
1322error message. We recommend using @code{getline} instead of @code{fgets}.
1323@end deftypefun
1324
b5e73f56 1325@deftypefun {wchar_t *} fgetws (wchar_t *@var{ws}, int @var{count}, FILE *@var{stream})
d08a7e4c 1326@standards{ISO, wchar.h}
171e9210 1327@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
b5e73f56
UD
1328The @code{fgetws} function reads wide characters from the stream
1329@var{stream} up to and including a newline character and stores them in
1330the string @var{ws}, adding a null wide character to mark the end of the
1331string. You must supply @var{count} wide characters worth of space in
1332@var{ws}, but the number of characters read is at most @var{count}
1333@minus{} 1. The extra character space is used to hold the null wide
1334character at the end of the string.
1335
1336If the system is already at end of file when you call @code{fgetws}, then
1337the contents of the array @var{ws} are unchanged and a null pointer is
1338returned. A null pointer is also returned if a read error occurs.
1339Otherwise, the return value is the pointer @var{ws}.
1340
1341@strong{Warning:} If the input data has a null wide character (which are
1342null bytes in the input stream), you can't tell. So don't use
1343@code{fgetws} unless you know the data cannot contain a null. Don't use
1344it to read files edited by the user because, if the user inserts a null
1345character, you should either handle it properly or print a clear error
1346message.
1347@comment XXX We need getwline!!!
1348@end deftypefun
1349
7b4161bb 1350@deftypefun {char *} fgets_unlocked (char *@var{s}, int @var{count}, FILE *@var{stream})
d08a7e4c 1351@standards{GNU, stdio.h}
171e9210 1352@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1353The @code{fgets_unlocked} function is equivalent to the @code{fgets}
1dc843f7 1354function except that it does not implicitly lock the stream.
7b4161bb
UD
1355
1356This function is a GNU extension.
1357@end deftypefun
1358
b5e73f56 1359@deftypefun {wchar_t *} fgetws_unlocked (wchar_t *@var{ws}, int @var{count}, FILE *@var{stream})
d08a7e4c 1360@standards{GNU, wchar.h}
171e9210 1361@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
b5e73f56 1362The @code{fgetws_unlocked} function is equivalent to the @code{fgetws}
1dc843f7 1363function except that it does not implicitly lock the stream.
b5e73f56
UD
1364
1365This function is a GNU extension.
1366@end deftypefun
1367
28f540f4 1368@deftypefn {Deprecated function} {char *} gets (char *@var{s})
d08a7e4c 1369@standards{ISO, stdio.h}
171e9210 1370@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1371The function @code{gets} reads characters from the stream @code{stdin}
1372up to the next newline character, and stores them in the string @var{s}.
1373The newline character is discarded (note that this differs from the
1374behavior of @code{fgets}, which copies the newline character into the
1375string). If @code{gets} encounters a read error or end-of-file, it
1376returns a null pointer; otherwise it returns @var{s}.
1377
1378@strong{Warning:} The @code{gets} function is @strong{very dangerous}
1379because it provides no protection against overflowing the string
1f77f049 1380@var{s}. @Theglibc{} includes it for compatibility only. You
28f540f4
RM
1381should @strong{always} use @code{fgets} or @code{getline} instead. To
1382remind you of this, the linker (if using GNU @code{ld}) will issue a
1383warning whenever you use @code{gets}.
1384@end deftypefn
1385
1386@node Unreading
1387@section Unreading
1388@cindex peeking at input
1389@cindex unreading characters
1390@cindex pushing input back
1391
1392In parser programs it is often useful to examine the next character in
1393the input stream without removing it from the stream. This is called
1394``peeking ahead'' at the input because your program gets a glimpse of
1395the input it will read next.
1396
1397Using stream I/O, you can peek ahead at input by first reading it and
19c3f208 1398then @dfn{unreading} it (also called @dfn{pushing it back} on the stream).
28f540f4
RM
1399Unreading a character makes it available to be input again from the stream,
1400by the next call to @code{fgetc} or other input function on that stream.
1401
1402@menu
1403* Unreading Idea:: An explanation of unreading with pictures.
1404* How Unread:: How to call @code{ungetc} to do unreading.
1405@end menu
1406
1407@node Unreading Idea
1408@subsection What Unreading Means
1409
1410Here is a pictorial explanation of unreading. Suppose you have a
1411stream reading a file that contains just six characters, the letters
1412@samp{foobar}. Suppose you have read three characters so far. The
1413situation looks like this:
1414
1415@smallexample
1416f o o b a r
162ba701 1417 ^
28f540f4
RM
1418@end smallexample
1419
1420@noindent
1421so the next input character will be @samp{b}.
1422
1423@c @group Invalid outside @example
1424If instead of reading @samp{b} you unread the letter @samp{o}, you get a
1425situation like this:
1426
1427@smallexample
1428f o o b a r
162ba701 1429 |
28f540f4
RM
1430 o--
1431 ^
1432@end smallexample
1433
1434@noindent
1435so that the next input characters will be @samp{o} and @samp{b}.
1436@c @end group
1437
1438@c @group
1439If you unread @samp{9} instead of @samp{o}, you get this situation:
1440
1441@smallexample
1442f o o b a r
162ba701 1443 |
28f540f4
RM
1444 9--
1445 ^
1446@end smallexample
1447
1448@noindent
1449so that the next input characters will be @samp{9} and @samp{b}.
1450@c @end group
1451
1452@node How Unread
1453@subsection Using @code{ungetc} To Do Unreading
19c3f208 1454
28f540f4
RM
1455The function to unread a character is called @code{ungetc}, because it
1456reverses the action of @code{getc}.
1457
28f540f4 1458@deftypefun int ungetc (int @var{c}, FILE *@var{stream})
d08a7e4c 1459@standards{ISO, stdio.h}
171e9210 1460@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1461The @code{ungetc} function pushes back the character @var{c} onto the
1462input stream @var{stream}. So the next input from @var{stream} will
1463read @var{c} before anything else.
1464
1465If @var{c} is @code{EOF}, @code{ungetc} does nothing and just returns
1466@code{EOF}. This lets you call @code{ungetc} with the return value of
1467@code{getc} without needing to check for an error from @code{getc}.
1468
1469The character that you push back doesn't have to be the same as the last
1470character that was actually read from the stream. In fact, it isn't
1471necessary to actually read any characters from the stream before
f4efd068
UD
1472unreading them with @code{ungetc}! But that is a strange way to write a
1473program; usually @code{ungetc} is used only to unread a character that
1f77f049 1474was just read from the same stream. @Theglibc{} supports this
f4efd068 1475even on files opened in binary mode, but other systems might not.
28f540f4 1476
1f77f049 1477@Theglibc{} only supports one character of pushback---in other
28f540f4
RM
1478words, it does not work to call @code{ungetc} twice without doing input
1479in between. Other systems might let you push back multiple characters;
1480then reading from the stream retrieves the characters in the reverse
1481order that they were pushed.
1482
1483Pushing back characters doesn't alter the file; only the internal
1484buffering for the stream is affected. If a file positioning function
a5a0310d
UD
1485(such as @code{fseek}, @code{fseeko} or @code{rewind}; @pxref{File
1486Positioning}) is called, any pending pushed-back characters are
1487discarded.
28f540f4
RM
1488
1489Unreading a character on a stream that is at end of file clears the
1490end-of-file indicator for the stream, because it makes the character of
1491input available. After you read that character, trying to read again
1492will encounter end of file.
1493@end deftypefun
1494
b5e73f56 1495@deftypefun wint_t ungetwc (wint_t @var{wc}, FILE *@var{stream})
d08a7e4c 1496@standards{ISO, wchar.h}
171e9210 1497@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
b5e73f56
UD
1498The @code{ungetwc} function behaves just like @code{ungetc} just that it
1499pushes back a wide character.
1500@end deftypefun
1501
28f540f4
RM
1502Here is an example showing the use of @code{getc} and @code{ungetc} to
1503skip over whitespace characters. When this function reaches a
1504non-whitespace character, it unreads that character to be seen again on
1505the next read operation on the stream.
1506
1507@smallexample
1508#include <stdio.h>
1509#include <ctype.h>
1510
1511void
1512skip_whitespace (FILE *stream)
1513@{
1514 int c;
1515 do
1516 /* @r{No need to check for @code{EOF} because it is not}
1517 @r{@code{isspace}, and @code{ungetc} ignores @code{EOF}.} */
1518 c = getc (stream);
1519 while (isspace (c));
1520 ungetc (c, stream);
1521@}
1522@end smallexample
1523
1524@node Block Input/Output
1525@section Block Input/Output
1526
1527This section describes how to do input and output operations on blocks
1528of data. You can use these functions to read and write binary data, as
1529well as to read and write text in fixed-size blocks instead of by
1530characters or lines.
1531@cindex binary I/O to a stream
1532@cindex block I/O to a stream
1533@cindex reading from a stream, by blocks
1534@cindex writing to a stream, by blocks
1535
1536Binary files are typically used to read and write blocks of data in the
1537same format as is used to represent the data in a running program. In
1538other words, arbitrary blocks of memory---not just character or string
1539objects---can be written to a binary file, and meaningfully read in
1540again by the same program.
1541
1542Storing data in binary form is often considerably more efficient than
1543using the formatted I/O functions. Also, for floating-point numbers,
1544the binary form avoids possible loss of precision in the conversion
1545process. On the other hand, binary files can't be examined or modified
1546easily using many standard file utilities (such as text editors), and
1547are not portable between different implementations of the language, or
1548different kinds of computers.
1549
1550These functions are declared in @file{stdio.h}.
1551@pindex stdio.h
1552
28f540f4 1553@deftypefun size_t fread (void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
d08a7e4c 1554@standards{ISO, stdio.h}
171e9210 1555@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1556This function reads up to @var{count} objects of size @var{size} into
1557the array @var{data}, from the stream @var{stream}. It returns the
1558number of objects actually read, which might be less than @var{count} if
1559a read error occurs or the end of the file is reached. This function
1560returns a value of zero (and doesn't read anything) if either @var{size}
1561or @var{count} is zero.
1562
1563If @code{fread} encounters end of file in the middle of an object, it
1564returns the number of complete objects read, and discards the partial
1565object. Therefore, the stream remains at the actual end of the file.
1566@end deftypefun
1567
7b4161bb 1568@deftypefun size_t fread_unlocked (void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
d08a7e4c 1569@standards{GNU, stdio.h}
171e9210 1570@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1571The @code{fread_unlocked} function is equivalent to the @code{fread}
1dc843f7 1572function except that it does not implicitly lock the stream.
7b4161bb
UD
1573
1574This function is a GNU extension.
1575@end deftypefun
1576
28f540f4 1577@deftypefun size_t fwrite (const void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
d08a7e4c 1578@standards{ISO, stdio.h}
171e9210 1579@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
1580This function writes up to @var{count} objects of size @var{size} from
1581the array @var{data}, to the stream @var{stream}. The return value is
1582normally @var{count}, if the call succeeds. Any other value indicates
1583some sort of error, such as running out of space.
1584@end deftypefun
1585
7b4161bb 1586@deftypefun size_t fwrite_unlocked (const void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
d08a7e4c 1587@standards{GNU, stdio.h}
171e9210 1588@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 1589The @code{fwrite_unlocked} function is equivalent to the @code{fwrite}
1dc843f7 1590function except that it does not implicitly lock the stream.
7b4161bb
UD
1591
1592This function is a GNU extension.
1593@end deftypefun
1594
28f540f4
RM
1595@node Formatted Output
1596@section Formatted Output
1597
1598@cindex format string, for @code{printf}
1599@cindex template, for @code{printf}
1600@cindex formatted output to a stream
1601@cindex writing to a stream, formatted
1602The functions described in this section (@code{printf} and related
1603functions) provide a convenient way to perform formatted output. You
1604call @code{printf} with a @dfn{format string} or @dfn{template string}
1605that specifies how to format the values of the remaining arguments.
1606
1607Unless your program is a filter that specifically performs line- or
1608character-oriented processing, using @code{printf} or one of the other
1609related functions described in this section is usually the easiest and
1610most concise way to perform output. These functions are especially
1611useful for printing error messages, tables of data, and the like.
1612
1613@menu
1614* Formatted Output Basics:: Some examples to get you started.
1615* Output Conversion Syntax:: General syntax of conversion
162ba701 1616 specifications.
28f540f4 1617* Table of Output Conversions:: Summary of output conversions and
162ba701 1618 what they do.
28f540f4
RM
1619* Integer Conversions:: Details about formatting of integers.
1620* Floating-Point Conversions:: Details about formatting of
162ba701 1621 floating-point numbers.
28f540f4 1622* Other Output Conversions:: Details about formatting of strings,
162ba701 1623 characters, pointers, and the like.
28f540f4
RM
1624* Formatted Output Functions:: Descriptions of the actual functions.
1625* Dynamic Output:: Functions that allocate memory for the output.
1626* Variable Arguments Output:: @code{vprintf} and friends.
1627* Parsing a Template String:: What kinds of args does a given template
162ba701 1628 call for?
28f540f4
RM
1629* Example of Parsing:: Sample program using @code{parse_printf_format}.
1630@end menu
1631
1632@node Formatted Output Basics
1633@subsection Formatted Output Basics
1634
1635The @code{printf} function can be used to print any number of arguments.
1636The template string argument you supply in a call provides
1637information not only about the number of additional arguments, but also
1638about their types and what style should be used for printing them.
1639
1640Ordinary characters in the template string are simply written to the
1641output stream as-is, while @dfn{conversion specifications} introduced by
1642a @samp{%} character in the template cause subsequent arguments to be
1643formatted and written to the output stream. For example,
1644@cindex conversion specifications (@code{printf})
1645
1646@smallexample
1647int pct = 37;
1648char filename[] = "foo.txt";
1649printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
162ba701 1650 filename, pct);
28f540f4
RM
1651@end smallexample
1652
1653@noindent
1654produces output like
1655
1656@smallexample
1657Processing of `foo.txt' is 37% finished.
1658Please be patient.
1659@end smallexample
1660
1661This example shows the use of the @samp{%d} conversion to specify that
1662an @code{int} argument should be printed in decimal notation, the
1663@samp{%s} conversion to specify printing of a string argument, and
1664the @samp{%%} conversion to print a literal @samp{%} character.
1665
1666There are also conversions for printing an integer argument as an
309548be
JM
1667unsigned value in binary, octal, decimal, or hexadecimal radix
1668(@samp{%b}, @samp{%o}, @samp{%u}, or @samp{%x}, respectively); or as a
1669character value (@samp{%c}).
28f540f4
RM
1670
1671Floating-point numbers can be printed in normal, fixed-point notation
1672using the @samp{%f} conversion or in exponential notation using the
1673@samp{%e} conversion. The @samp{%g} conversion uses either @samp{%e}
1674or @samp{%f} format, depending on what is more appropriate for the
1675magnitude of the particular number.
1676
1677You can control formatting more precisely by writing @dfn{modifiers}
1678between the @samp{%} and the character that indicates which conversion
1679to apply. These slightly alter the ordinary behavior of the conversion.
1680For example, most conversion specifications permit you to specify a
1681minimum field width and a flag indicating whether you want the result
1682left- or right-justified within the field.
1683
1684The specific flags and modifiers that are permitted and their
1685interpretation vary depending on the particular conversion. They're all
1686described in more detail in the following sections. Don't worry if this
1687all seems excessively complicated at first; you can almost always get
1688reasonable free-format output without using any of the modifiers at all.
1689The modifiers are mostly used to make the output look ``prettier'' in
1690tables.
1691
1692@node Output Conversion Syntax
1693@subsection Output Conversion Syntax
1694
1695This section provides details about the precise syntax of conversion
1696specifications that can appear in a @code{printf} template
1697string.
1698
390955cb
UD
1699Characters in the template string that are not part of a conversion
1700specification are printed as-is to the output stream. Multibyte
1701character sequences (@pxref{Character Set Handling}) are permitted in a
1702template string.
28f540f4
RM
1703
1704The conversion specifications in a @code{printf} template string have
1705the general form:
1706
f89829da 1707@smallexample
dfd2257a 1708% @r{[} @var{param-no} @r{$]} @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion}
f89829da
UD
1709@end smallexample
1710
1711@noindent
1712or
1713
1714@smallexample
1715% @r{[} @var{param-no} @r{$]} @var{flags} @var{width} . @r{*} @r{[} @var{param-no} @r{$]} @var{type} @var{conversion}
1716@end smallexample
28f540f4
RM
1717
1718For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-}
1719is a flag, @samp{10} specifies the field width, the precision is
1720@samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies
1721the conversion style. (This particular type specifier says to
1722print a @code{long int} argument in decimal notation, with a minimum of
17238 digits left-justified in a field at least 10 characters wide.)
1724
1725In more detail, output conversion specifications consist of an
1726initial @samp{%} character followed in sequence by:
1727
1728@itemize @bullet
dfd2257a
UD
1729@item
1730An optional specification of the parameter used for this format.
e8b1163e 1731Normally the parameters to the @code{printf} function are assigned to the
f2ea0f5b 1732formats in the order of appearance in the format string. But in some
dfd2257a 1733situations (such as message translation) this is not desirable and this
e8b1163e 1734extension allows an explicit parameter to be specified.
dfd2257a 1735
f89829da 1736The @var{param-no} parts of the format must be integers in the range of
dfd2257a 17371 to the maximum number of arguments present to the function call. Some
c703cd7a 1738implementations limit this number to a certain upper bound. The exact
dfd2257a
UD
1739limit can be retrieved by the following constant.
1740
1741@defvr Macro NL_ARGMAX
f89829da 1742The value of @code{NL_ARGMAX} is the maximum value allowed for the
9dcc8f11 1743specification of a positional parameter in a @code{printf} call. The
dfd2257a
UD
1744actual value in effect at runtime can be retrieved by using
1745@code{sysconf} using the @code{_SC_NL_ARGMAX} parameter @pxref{Sysconf
1746Definition}.
1747
c703cd7a 1748Some systems have a quite low limit such as @math{9} for @w{System V}
1f77f049 1749systems. @Theglibc{} has no real limit.
dfd2257a
UD
1750@end defvr
1751
1752If any of the formats has a specification for the parameter position all
0bc93a2f 1753of them in the format string shall have one. Otherwise the behavior is
dfd2257a
UD
1754undefined.
1755
19c3f208 1756@item
28f540f4
RM
1757Zero or more @dfn{flag characters} that modify the normal behavior of
1758the conversion specification.
1759@cindex flag character (@code{printf})
1760
19c3f208 1761@item
28f540f4
RM
1762An optional decimal integer specifying the @dfn{minimum field width}.
1763If the normal conversion produces fewer characters than this, the field
1764is padded with spaces to the specified width. This is a @emph{minimum}
1765value; if the normal conversion produces more characters than this, the
1766field is @emph{not} truncated. Normally, the output is right-justified
1767within the field.
1768@cindex minimum field width (@code{printf})
1769
1770You can also specify a field width of @samp{*}. This means that the
1771next argument in the argument list (before the actual value to be
1772printed) is used as the field width. The value must be an @code{int}.
1773If the value is negative, this means to set the @samp{-} flag (see
1774below) and to use the absolute value as the field width.
1775
19c3f208 1776@item
28f540f4
RM
1777An optional @dfn{precision} to specify the number of digits to be
1778written for the numeric conversions. If the precision is specified, it
1779consists of a period (@samp{.}) followed optionally by a decimal integer
1780(which defaults to zero if omitted).
1781@cindex precision (@code{printf})
1782
1783You can also specify a precision of @samp{*}. This means that the next
1784argument in the argument list (before the actual value to be printed) is
1785used as the precision. The value must be an @code{int}, and is ignored
1786if it is negative. If you specify @samp{*} for both the field width and
1787precision, the field width argument precedes the precision argument.
1788Other C library versions may not recognize this syntax.
1789
1790@item
1791An optional @dfn{type modifier character}, which is used to specify the
1792data type of the corresponding argument if it differs from the default
1793type. (For example, the integer conversions assume a type of @code{int},
1794but you can specify @samp{h}, @samp{l}, or @samp{L} for other integer
1795types.)
1796@cindex type modifier character (@code{printf})
1797
1798@item
1799A character that specifies the conversion to be applied.
1800@end itemize
1801
19c3f208 1802The exact options that are permitted and how they are interpreted vary
28f540f4
RM
1803between the different conversion specifiers. See the descriptions of the
1804individual conversions for information about the particular options that
1805they use.
1806
1807With the @samp{-Wformat} option, the GNU C compiler checks calls to
1808@code{printf} and related functions. It examines the format string and
1809verifies that the correct number and types of arguments are supplied.
1810There is also a GNU C syntax to tell the compiler that a function you
19c3f208 1811write uses a @code{printf}-style format string.
28f540f4 1812@xref{Function Attributes, , Declaring Attributes of Functions,
1f6676d7 1813gcc, Using GNU CC}, for more information.
28f540f4
RM
1814
1815@node Table of Output Conversions
1816@subsection Table of Output Conversions
1817@cindex output conversions, for @code{printf}
1818
1819Here is a table summarizing what all the different conversions do:
1820
1821@table @asis
1822@item @samp{%d}, @samp{%i}
1823Print an integer as a signed decimal number. @xref{Integer
1824Conversions}, for details. @samp{%d} and @samp{%i} are synonymous for
1825output, but are different when used with @code{scanf} for input
1826(@pxref{Table of Input Conversions}).
1827
309548be
JM
1828@item @samp{%b}, @samp{%B}
1829Print an integer as an unsigned binary number. @samp{%b} uses
1830lower-case @samp{b} with the @samp{#} flag and @samp{%B} uses
1831upper-case. @samp{%b} is an ISO C2X feature; @samp{%B} is an
2d4728e6 1832optional ISO C2X feature. @xref{Integer Conversions}, for
309548be
JM
1833details.
1834
28f540f4
RM
1835@item @samp{%o}
1836Print an integer as an unsigned octal number. @xref{Integer
1837Conversions}, for details.
1838
1839@item @samp{%u}
1840Print an integer as an unsigned decimal number. @xref{Integer
1841Conversions}, for details.
1842
1843@item @samp{%x}, @samp{%X}
1844Print an integer as an unsigned hexadecimal number. @samp{%x} uses
1845lower-case letters and @samp{%X} uses upper-case. @xref{Integer
1846Conversions}, for details.
1847
0674613e 1848@item @samp{%f}, @samp{%F}
28f540f4 1849Print a floating-point number in normal (fixed-point) notation.
0674613e 1850@samp{%f} uses lower-case letters and @samp{%F} uses upper-case.
28f540f4
RM
1851@xref{Floating-Point Conversions}, for details.
1852
1853@item @samp{%e}, @samp{%E}
1854Print a floating-point number in exponential notation. @samp{%e} uses
1855lower-case letters and @samp{%E} uses upper-case. @xref{Floating-Point
1856Conversions}, for details.
1857
1858@item @samp{%g}, @samp{%G}
1859Print a floating-point number in either normal or exponential notation,
1860whichever is more appropriate for its magnitude. @samp{%g} uses
1861lower-case letters and @samp{%G} uses upper-case. @xref{Floating-Point
1862Conversions}, for details.
1863
2f6d1f1b 1864@item @samp{%a}, @samp{%A}
c703cd7a 1865Print a floating-point number in a hexadecimal fractional notation with
2f6d1f1b
UD
1866the exponent to base 2 represented in decimal digits. @samp{%a} uses
1867lower-case letters and @samp{%A} uses upper-case. @xref{Floating-Point
1868Conversions}, for details.
1869
28f540f4
RM
1870@item @samp{%c}
1871Print a single character. @xref{Other Output Conversions}.
1872
b5e73f56
UD
1873@item @samp{%C}
1874This is an alias for @samp{%lc} which is supported for compatibility
1875with the Unix standard.
1876
28f540f4
RM
1877@item @samp{%s}
1878Print a string. @xref{Other Output Conversions}.
1879
b5e73f56
UD
1880@item @samp{%S}
1881This is an alias for @samp{%ls} which is supported for compatibility
1882with the Unix standard.
1883
28f540f4
RM
1884@item @samp{%p}
1885Print the value of a pointer. @xref{Other Output Conversions}.
1886
1887@item @samp{%n}
1888Get the number of characters printed so far. @xref{Other Output Conversions}.
1889Note that this conversion specification never produces any output.
1890
1891@item @samp{%m}
1892Print the string corresponding to the value of @code{errno}.
1893(This is a GNU extension.)
1894@xref{Other Output Conversions}.
1895
1896@item @samp{%%}
1897Print a literal @samp{%} character. @xref{Other Output Conversions}.
1898@end table
1899
1900If the syntax of a conversion specification is invalid, unpredictable
1901things will happen, so don't do this. If there aren't enough function
1902arguments provided to supply values for all the conversion
1903specifications in the template string, or if the arguments are not of
1904the correct types, the results are unpredictable. If you supply more
1905arguments than conversion specifications, the extra argument values are
1906simply ignored; this is sometimes useful.
1907
1908@node Integer Conversions
1909@subsection Integer Conversions
1910
1911This section describes the options for the @samp{%d}, @samp{%i},
309548be 1912@samp{%b}, @samp{%B}, @samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion
28f540f4
RM
1913specifications. These conversions print integers in various formats.
1914
1915The @samp{%d} and @samp{%i} conversion specifications both print an
a35c960d 1916@code{int} argument as a signed decimal number; while @samp{%b}, @samp{%o},
309548be 1917@samp{%u}, and @samp{%x} print the argument as an unsigned binary, octal,
28f540f4
RM
1918decimal, or hexadecimal number (respectively). The @samp{%X} conversion
1919specification is just like @samp{%x} except that it uses the characters
309548be
JM
1920@samp{ABCDEF} as digits instead of @samp{abcdef}. The @samp{%B}
1921conversion specification is just like @samp{%b} except that, with the
1922@samp{#} flag, the output starts with @samp{0B} instead of @samp{0b}.
28f540f4
RM
1923
1924The following flags are meaningful:
1925
1926@table @asis
1927@item @samp{-}
1928Left-justify the result in the field (instead of the normal
1929right-justification).
1930
1931@item @samp{+}
1932For the signed @samp{%d} and @samp{%i} conversions, print a
1933plus sign if the value is positive.
1934
1935@item @samp{ }
1936For the signed @samp{%d} and @samp{%i} conversions, if the result
1937doesn't start with a plus or minus sign, prefix it with a space
1938character instead. Since the @samp{+} flag ensures that the result
1939includes a sign, this flag is ignored if you supply both of them.
1940
1941@item @samp{#}
1942For the @samp{%o} conversion, this forces the leading digit to be
1943@samp{0}, as if by increasing the precision. For @samp{%x} or
309548be
JM
1944@samp{%X}, this prefixes a leading @samp{0x} or @samp{0X}
1945(respectively) to the result. For @samp{%b} or @samp{%B}, this
1946prefixes a leading @samp{0b} or @samp{0B} (respectively)
28f540f4
RM
1947to the result. This doesn't do anything useful for the @samp{%d},
1948@samp{%i}, or @samp{%u} conversions. Using this flag produces output
1949which can be parsed by the @code{strtoul} function (@pxref{Parsing of
1950Integers}) and @code{scanf} with the @samp{%i} conversion
1951(@pxref{Numeric Input Conversions}).
1952
9702a790
FW
1953For the @samp{%m} conversion, print an error constant or decimal error
1954number, instead of a (possibly translated) error message.
1955
28f540f4
RM
1956@item @samp{'}
1957Separate the digits into groups as specified by the locale specified for
1958the @code{LC_NUMERIC} category; @pxref{General Numeric}. This flag is a
1959GNU extension.
1960
1961@item @samp{0}
1962Pad the field with zeros instead of spaces. The zeros are placed after
1963any indication of sign or base. This flag is ignored if the @samp{-}
1964flag is also specified, or if a precision is specified.
1965@end table
1966
1967If a precision is supplied, it specifies the minimum number of digits to
1968appear; leading zeros are produced if necessary. If you don't specify a
1969precision, the number is printed with as many digits as it needs. If
1970you convert a value of zero with an explicit precision of zero, then no
1971characters at all are produced.
1972
1973Without a type modifier, the corresponding argument is treated as an
1974@code{int} (for the signed conversions @samp{%i} and @samp{%d}) or
309548be
JM
1975@code{unsigned int} (for the unsigned conversions @samp{%b},
1976@samp{%B}, @samp{%o}, @samp{%u},
28f540f4
RM
1977@samp{%x}, and @samp{%X}). Recall that since @code{printf} and friends
1978are variadic, any @code{char} and @code{short} arguments are
1979automatically converted to @code{int} by the default argument
1980promotions. For arguments of other integer types, you can use these
1981modifiers:
1982
1983@table @samp
cc3fa755
UD
1984@item hh
1985Specifies that the argument is a @code{signed char} or @code{unsigned
1986char}, as appropriate. A @code{char} argument is converted to an
1987@code{int} or @code{unsigned int} by the default argument promotions
c703cd7a 1988anyway, but the @samp{hh} modifier says to convert it back to a
cc3fa755
UD
1989@code{char} again.
1990
ec751a23 1991This modifier was introduced in @w{ISO C99}.
e852e889 1992
28f540f4
RM
1993@item h
1994Specifies that the argument is a @code{short int} or @code{unsigned
1995short int}, as appropriate. A @code{short} argument is converted to an
1996@code{int} or @code{unsigned int} by the default argument promotions
1997anyway, but the @samp{h} modifier says to convert it back to a
1998@code{short} again.
1999
e852e889
UD
2000@item j
2001Specifies that the argument is a @code{intmax_t} or @code{uintmax_t}, as
2002appropriate.
2003
ec751a23 2004This modifier was introduced in @w{ISO C99}.
e852e889 2005
28f540f4
RM
2006@item l
2007Specifies that the argument is a @code{long int} or @code{unsigned long
c703cd7a 2008int}, as appropriate. Two @samp{l} characters are like the @samp{L}
28f540f4
RM
2009modifier, below.
2010
b5e73f56
UD
2011If used with @samp{%c} or @samp{%s} the corresponding parameter is
2012considered as a wide character or wide character string respectively.
2013This use of @samp{l} was introduced in @w{Amendment 1} to @w{ISO C90}.
2014
28f540f4
RM
2015@item L
2016@itemx ll
2017@itemx q
2018Specifies that the argument is a @code{long long int}. (This type is
2019an extension supported by the GNU C compiler. On systems that don't
2020support extra-long integers, this is the same as @code{long int}.)
2021
2022The @samp{q} modifier is another name for the same thing, which comes
2023from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
2024@code{int}.
2025
e852e889
UD
2026@item t
2027Specifies that the argument is a @code{ptrdiff_t}.
2028
ec751a23 2029This modifier was introduced in @w{ISO C99}.
e852e889
UD
2030
2031@item z
2032@itemx Z
2033Specifies that the argument is a @code{size_t}.
2034
ec751a23 2035@samp{z} was introduced in @w{ISO C99}. @samp{Z} is a GNU extension
0be8752b 2036predating this addition and should not be used in new code.
28f540f4
RM
2037@end table
2038
2039Here is an example. Using the template string:
2040
2041@smallexample
2042"|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
2043@end smallexample
2044
2045@noindent
2046to print numbers using the different options for the @samp{%d}
2047conversion gives results like:
2048
2049@smallexample
2050| 0|0 | +0|+0 | 0|00000| | 00|0|
2051| 1|1 | +1|+1 | 1|00001| 1| 01|1|
2052| -1|-1 | -1|-1 | -1|-0001| -1| -01|-1|
776e8492 2053|100000|100000|+100000|+100000| 100000|100000|100000|100000|100000|
28f540f4
RM
2054@end smallexample
2055
2056In particular, notice what happens in the last case where the number
2057is too large to fit in the minimum field width specified.
2058
2059Here are some more examples showing how unsigned integers print under
2060various format options, using the template string:
2061
2062@smallexample
2063"|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"
2064@end smallexample
2065
2066@smallexample
776e8492 2067| 0| 0| 0| 0| 0| 0| 0| 00000000|
28f540f4
RM
2068| 1| 1| 1| 1| 01| 0x1| 0X1|0x00000001|
2069|100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|
2070@end smallexample
2071
2072
2073@node Floating-Point Conversions
2074@subsection Floating-Point Conversions
2075
2076This section discusses the conversion specifications for floating-point
0674613e
PP
2077numbers: the @samp{%f}, @samp{%F}, @samp{%e}, @samp{%E}, @samp{%g}, and
2078@samp{%G} conversions.
28f540f4 2079
0674613e
PP
2080The @samp{%f} and @samp{%F} conversions print their argument in fixed-point
2081notation, producing output of the form
28f540f4
RM
2082@w{[@code{-}]@var{ddd}@code{.}@var{ddd}},
2083where the number of digits following the decimal point is controlled
2084by the precision you specify.
2085
2086The @samp{%e} conversion prints its argument in exponential notation,
2087producing output of the form
2088@w{[@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}}.
2089Again, the number of digits following the decimal point is controlled by
2090the precision. The exponent always contains at least two digits. The
2091@samp{%E} conversion is similar but the exponent is marked with the letter
2092@samp{E} instead of @samp{e}.
2093
2094The @samp{%g} and @samp{%G} conversions print the argument in the style
2095of @samp{%e} or @samp{%E} (respectively) if the exponent would be less
776e8492 2096than -4 or greater than or equal to the precision; otherwise they use
0674613e 2097the @samp{%f} or @samp{%F} style. A precision of @code{0}, is taken as 1.
776e8492
AJ
2098Trailing zeros are removed from the fractional portion of the result and
2099a decimal-point character appears only if it is followed by a digit.
28f540f4 2100
2f6d1f1b 2101The @samp{%a} and @samp{%A} conversions are meant for representing
0be8752b 2102floating-point numbers exactly in textual form so that they can be
2f6d1f1b 2103exchanged as texts between different programs and/or machines. The
c703cd7a 2104numbers are represented in the form
2f6d1f1b
UD
2105@w{[@code{-}]@code{0x}@var{h}@code{.}@var{hhh}@code{p}[@code{+}|@code{-}]@var{dd}}.
2106At the left of the decimal-point character exactly one digit is print.
91ea72b7 2107This character is only @code{0} if the number is denormalized.
49c091e5 2108Otherwise the value is unspecified; it is implementation dependent how many
2f6d1f1b
UD
2109bits are used. The number of hexadecimal digits on the right side of
2110the decimal-point character is equal to the precision. If the precision
2111is zero it is determined to be large enough to provide an exact
2112representation of the number (or it is large enough to distinguish two
2113adjacent values if the @code{FLT_RADIX} is not a power of 2,
91ea72b7 2114@pxref{Floating Point Parameters}). For the @samp{%a} conversion
2f6d1f1b
UD
2115lower-case characters are used to represent the hexadecimal number and
2116the prefix and exponent sign are printed as @code{0x} and @code{p}
2117respectively. Otherwise upper-case characters are used and @code{0X}
2118and @code{P} are used for the representation of prefix and exponent
2119string. The exponent to the base of two is printed as a decimal number
2120using at least one digit but at most as many digits as necessary to
2121represent the value exactly.
2122
2123If the value to be printed represents infinity or a NaN, the output is
2124@w{[@code{-}]@code{inf}} or @code{nan} respectively if the conversion
2125specifier is @samp{%a}, @samp{%e}, @samp{%f}, or @samp{%g} and it is
2126@w{[@code{-}]@code{INF}} or @code{NAN} respectively if the conversion is
0674613e 2127@samp{%A}, @samp{%E}, @samp{%F} or @samp{%G}. On some implementations, a NaN
01d34e93
JM
2128may result in longer output with information about the payload of the
2129NaN; ISO C2X defines a macro @code{_PRINTF_NAN_LEN_MAX} giving the
2130maximum length of such output.
2f6d1f1b 2131
28f540f4
RM
2132The following flags can be used to modify the behavior:
2133
2134@comment We use @asis instead of @samp so we can have ` ' as an item.
2135@table @asis
2136@item @samp{-}
2137Left-justify the result in the field. Normally the result is
2138right-justified.
2139
2140@item @samp{+}
2141Always include a plus or minus sign in the result.
2142
2143@item @samp{ }
2144If the result doesn't start with a plus or minus sign, prefix it with a
2145space instead. Since the @samp{+} flag ensures that the result includes
2146a sign, this flag is ignored if you supply both of them.
2147
2148@item @samp{#}
2149Specifies that the result should always include a decimal point, even
2150if no digits follow it. For the @samp{%g} and @samp{%G} conversions,
2151this also forces trailing zeros after the decimal point to be left
2152in place where they would otherwise be removed.
2153
2154@item @samp{'}
2155Separate the digits of the integer part of the result into groups as
2156specified by the locale specified for the @code{LC_NUMERIC} category;
2157@pxref{General Numeric}. This flag is a GNU extension.
2158
2159@item @samp{0}
2160Pad the field with zeros instead of spaces; the zeros are placed
2161after any sign. This flag is ignored if the @samp{-} flag is also
2162specified.
2163@end table
2164
2165The precision specifies how many digits follow the decimal-point
0674613e
PP
2166character for the @samp{%f}, @samp{%F}, @samp{%e}, and @samp{%E} conversions.
2167For these conversions, the default precision is @code{6}. If the precision
28f540f4
RM
2168is explicitly @code{0}, this suppresses the decimal point character
2169entirely. For the @samp{%g} and @samp{%G} conversions, the precision
2170specifies how many significant digits to print. Significant digits are
2171the first digit before the decimal point, and all the digits after it.
91ea72b7 2172If the precision is @code{0} or not specified for @samp{%g} or @samp{%G},
28f540f4
RM
2173it is treated like a value of @code{1}. If the value being printed
2174cannot be expressed accurately in the specified number of digits, the
2175value is rounded to the nearest number that fits.
2176
2177Without a type modifier, the floating-point conversions use an argument
2178of type @code{double}. (By the default argument promotions, any
2179@code{float} arguments are automatically converted to @code{double}.)
2180The following type modifier is supported:
2181
2182@table @samp
2183@item L
2184An uppercase @samp{L} specifies that the argument is a @code{long
2185double}.
2186@end table
2187
2188Here are some examples showing how numbers print using the various
2189floating-point conversions. All of the numbers were printed using
2190this template string:
2191
2192@smallexample
2f6d1f1b 2193"|%13.4a|%13.4f|%13.4e|%13.4g|\n"
28f540f4
RM
2194@end smallexample
2195
2196Here is the output:
2197
2198@smallexample
2f6d1f1b
UD
2199| 0x0.0000p+0| 0.0000| 0.0000e+00| 0|
2200| 0x1.0000p-1| 0.5000| 5.0000e-01| 0.5|
2201| 0x1.0000p+0| 1.0000| 1.0000e+00| 1|
2202| -0x1.0000p+0| -1.0000| -1.0000e+00| -1|
2203| 0x1.9000p+6| 100.0000| 1.0000e+02| 100|
2204| 0x1.f400p+9| 1000.0000| 1.0000e+03| 1000|
2205| 0x1.3880p+13| 10000.0000| 1.0000e+04| 1e+04|
2206| 0x1.81c8p+13| 12345.0000| 1.2345e+04| 1.234e+04|
2207| 0x1.86a0p+16| 100000.0000| 1.0000e+05| 1e+05|
2208| 0x1.e240p+16| 123456.0000| 1.2346e+05| 1.235e+05|
28f540f4
RM
2209@end smallexample
2210
2211Notice how the @samp{%g} conversion drops trailing zeros.
2212
2213@node Other Output Conversions
2214@subsection Other Output Conversions
2215
2216This section describes miscellaneous conversions for @code{printf}.
2217
b5e73f56
UD
2218The @samp{%c} conversion prints a single character. In case there is no
2219@samp{l} modifier the @code{int} argument is first converted to an
2220@code{unsigned char}. Then, if used in a wide stream function, the
2221character is converted into the corresponding wide character. The
2222@samp{-} flag can be used to specify left-justification in the field,
2223but no other flags are defined, and no precision or type modifier can be
2224given. For example:
28f540f4
RM
2225
2226@smallexample
2227printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');
2228@end smallexample
2229
2230@noindent
2231prints @samp{hello}.
2232
c703cd7a 2233If there is an @samp{l} modifier present the argument is expected to be
b5e73f56
UD
2234of type @code{wint_t}. If used in a multibyte function the wide
2235character is converted into a multibyte character before being added to
2236the output. In this case more than one output byte can be produced.
2237
2238The @samp{%s} conversion prints a string. If no @samp{l} modifier is
2239present the corresponding argument must be of type @code{char *} (or
2240@code{const char *}). If used in a wide stream function the string is
c703cd7a 2241first converted to a wide character string. A precision can be
b5e73f56 2242specified to indicate the maximum number of characters to write;
28f540f4
RM
2243otherwise characters in the string up to but not including the
2244terminating null character are written to the output stream. The
2245@samp{-} flag can be used to specify left-justification in the field,
2246but no other flags or type modifiers are defined for this conversion.
2247For example:
2248
2249@smallexample
2250printf ("%3s%-6s", "no", "where");
2251@end smallexample
2252
2253@noindent
2254prints @samp{ nowhere }.
2255
c703cd7a
RJ
2256If there is an @samp{l} modifier present, the argument is expected to
2257be of type @code{wchar_t} (or @code{const wchar_t *}).
b5e73f56 2258
28f540f4 2259If you accidentally pass a null pointer as the argument for a @samp{%s}
1f77f049 2260conversion, @theglibc{} prints it as @samp{(null)}. We think this
28f540f4
RM
2261is more useful than crashing. But it's not good practice to pass a null
2262argument intentionally.
2263
2264The @samp{%m} conversion prints the string corresponding to the error
2265code in @code{errno}. @xref{Error Messages}. Thus:
2266
2267@smallexample
2268fprintf (stderr, "can't open `%s': %m\n", filename);
2269@end smallexample
2270
2271@noindent
2272is equivalent to:
2273
2274@smallexample
2275fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
2276@end smallexample
2277
9702a790
FW
2278The @samp{%m} conversion can be used with the @samp{#} flag to print an
2279error constant, as provided by @code{strerrorname_np}. Both @samp{%m}
2280and @samp{%#m} are @glibcadj{} extensions.
28f540f4
RM
2281
2282The @samp{%p} conversion prints a pointer value. The corresponding
2283argument must be of type @code{void *}. In practice, you can use any
2284type of pointer.
2285
a7a93d50 2286In @theglibc{}, non-null pointers are printed as unsigned integers,
28f540f4
RM
2287as if a @samp{%#x} conversion were used. Null pointers print as
2288@samp{(nil)}. (Pointers might print differently in other systems.)
2289
2290For example:
2291
2292@smallexample
2293printf ("%p", "testing");
2294@end smallexample
2295
2296@noindent
2297prints @samp{0x} followed by a hexadecimal number---the address of the
2298string constant @code{"testing"}. It does not print the word
2299@samp{testing}.
2300
2301You can supply the @samp{-} flag with the @samp{%p} conversion to
2302specify left-justification, but no other flags, precision, or type
2303modifiers are defined.
2304
2305The @samp{%n} conversion is unlike any of the other output conversions.
2306It uses an argument which must be a pointer to an @code{int}, but
2307instead of printing anything it stores the number of characters printed
2308so far by this call at that location. The @samp{h} and @samp{l} type
2309modifiers are permitted to specify that the argument is of type
2310@code{short int *} or @code{long int *} instead of @code{int *}, but no
2311flags, field width, or precision are permitted.
2312
2313For example,
2314
2315@smallexample
2316int nchar;
2317printf ("%d %s%n\n", 3, "bears", &nchar);
2318@end smallexample
2319
2320@noindent
2321prints:
2322
2323@smallexample
23243 bears
2325@end smallexample
2326
2327@noindent
19c3f208 2328and sets @code{nchar} to @code{7}, because @samp{3 bears} is seven
28f540f4
RM
2329characters.
2330
2331
2332The @samp{%%} conversion prints a literal @samp{%} character. This
2333conversion doesn't use an argument, and no flags, field width,
2334precision, or type modifiers are permitted.
2335
2336
2337@node Formatted Output Functions
2338@subsection Formatted Output Functions
2339
2340This section describes how to call @code{printf} and related functions.
2341Prototypes for these functions are in the header file @file{stdio.h}.
2342Because these functions take a variable number of arguments, you
2343@emph{must} declare prototypes for them before using them. Of course,
2344the easiest way to make sure you have all the right prototypes is to
2345just include @file{stdio.h}.
2346@pindex stdio.h
2347
28f540f4 2348@deftypefun int printf (const char *@var{template}, @dots{})
d08a7e4c 2349@standards{ISO, stdio.h}
171e9210 2350@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
2351The @code{printf} function prints the optional arguments under the
2352control of the template string @var{template} to the stream
2353@code{stdout}. It returns the number of characters printed, or a
2354negative value if there was an output error.
2355@end deftypefun
2356
b5e73f56 2357@deftypefun int wprintf (const wchar_t *@var{template}, @dots{})
d08a7e4c 2358@standards{ISO, wchar.h}
171e9210 2359@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
2360The @code{wprintf} function prints the optional arguments under the
2361control of the wide template string @var{template} to the stream
2362@code{stdout}. It returns the number of wide characters printed, or a
2363negative value if there was an output error.
2364@end deftypefun
2365
28f540f4 2366@deftypefun int fprintf (FILE *@var{stream}, const char *@var{template}, @dots{})
d08a7e4c 2367@standards{ISO, stdio.h}
171e9210 2368@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
2369This function is just like @code{printf}, except that the output is
2370written to the stream @var{stream} instead of @code{stdout}.
2371@end deftypefun
2372
b5e73f56 2373@deftypefun int fwprintf (FILE *@var{stream}, const wchar_t *@var{template}, @dots{})
d08a7e4c 2374@standards{ISO, wchar.h}
171e9210 2375@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
2376This function is just like @code{wprintf}, except that the output is
2377written to the stream @var{stream} instead of @code{stdout}.
2378@end deftypefun
2379
28f540f4 2380@deftypefun int sprintf (char *@var{s}, const char *@var{template}, @dots{})
d08a7e4c 2381@standards{ISO, stdio.h}
171e9210 2382@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2383This is like @code{printf}, except that the output is stored in the character
2384array @var{s} instead of written to a stream. A null character is written
2385to mark the end of the string.
2386
2387The @code{sprintf} function returns the number of characters stored in
2388the array @var{s}, not including the terminating null character.
2389
2390The behavior of this function is undefined if copying takes place
2391between objects that overlap---for example, if @var{s} is also given
2392as an argument to be printed under control of the @samp{%s} conversion.
0a13c9e9 2393@xref{Copying Strings and Arrays}.
28f540f4
RM
2394
2395@strong{Warning:} The @code{sprintf} function can be @strong{dangerous}
2396because it can potentially output more characters than can fit in the
2397allocation size of the string @var{s}. Remember that the field width
2398given in a conversion specification is only a @emph{minimum} value.
2399
2400To avoid this problem, you can use @code{snprintf} or @code{asprintf},
2401described below.
2402@end deftypefun
2403
c703cd7a 2404@deftypefun int swprintf (wchar_t *@var{ws}, size_t @var{size}, const wchar_t *@var{template}, @dots{})
d08a7e4c 2405@standards{GNU, wchar.h}
171e9210 2406@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b5e73f56
UD
2407This is like @code{wprintf}, except that the output is stored in the
2408wide character array @var{ws} instead of written to a stream. A null
2409wide character is written to mark the end of the string. The @var{size}
2410argument specifies the maximum number of characters to produce. The
2411trailing null character is counted towards this limit, so you should
2412allocate at least @var{size} wide characters for the string @var{ws}.
2413
2f278c94
UD
2414The return value is the number of characters generated for the given
2415input, excluding the trailing null. If not all output fits into the
118816de
FW
2416provided buffer a negative value is returned, and @code{errno} is set to
2417@code{E2BIG}. (The setting of @code{errno} is a GNU extension.) You
2418should try again with a bigger output string. @emph{Note:} this is
2419different from how @code{snprintf} handles this situation.
b5e73f56
UD
2420
2421Note that the corresponding narrow stream function takes fewer
2422parameters. @code{swprintf} in fact corresponds to the @code{snprintf}
2423function. Since the @code{sprintf} function can be dangerous and should
2424be avoided the @w{ISO C} committee refused to make the same mistake
9dcc8f11 2425again and decided to not define a function exactly corresponding to
b5e73f56
UD
2426@code{sprintf}.
2427@end deftypefun
2428
28f540f4 2429@deftypefun int snprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, @dots{})
d08a7e4c 2430@standards{GNU, stdio.h}
171e9210 2431@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2432The @code{snprintf} function is similar to @code{sprintf}, except that
2433the @var{size} argument specifies the maximum number of characters to
2434produce. The trailing null character is counted towards this limit, so
2435you should allocate at least @var{size} characters for the string @var{s}.
42443a47
JL
2436If @var{size} is zero, nothing, not even the null byte, shall be written and
2437@var{s} may be a null pointer.
28f540f4 2438
fe7bdd63 2439The return value is the number of characters which would be generated
da2d1bc5 2440for the given input, excluding the trailing null. If this value is
c703cd7a 2441greater than or equal to @var{size}, not all characters from the result have
f173e272
PE
2442been stored in @var{s}. If this happens, you should be wary of using
2443the truncated result as that could lead to security, encoding, or
2444other bugs in your program (@pxref{Truncating Strings}).
2445Instead, you should try again with a bigger output
da2d1bc5 2446string. Here is an example of doing this:
28f540f4
RM
2447
2448@smallexample
2449@group
2450/* @r{Construct a message describing the value of a variable}
2451 @r{whose name is @var{name} and whose value is @var{value}.} */
2452char *
2453make_message (char *name, char *value)
2454@{
bdc674d9
PE
2455 /* @r{Guess we need no more than 100 bytes of space.} */
2456 size_t size = 100;
2457 char *buffer = xmalloc (size);
28f540f4
RM
2458@end group
2459@group
4cca6b86 2460 /* @r{Try to print in the allocated space.} */
bdc674d9
PE
2461 int buflen = snprintf (buffer, size, "value of %s is %s",
2462 name, value);
2463 if (! (0 <= buflen && buflen < SIZE_MAX))
2464 fatal ("integer overflow");
4cca6b86
UD
2465@end group
2466@group
bdc674d9 2467 if (buflen >= size)
28f540f4 2468 @{
4b8f94d3 2469 /* @r{Reallocate buffer now that we know
162ba701 2470 how much space is needed.} */
bdc674d9
PE
2471 size = buflen;
2472 size++;
2473 buffer = xrealloc (buffer, size);
4cca6b86 2474
bdc674d9
PE
2475 /* @r{Try again.} */
2476 snprintf (buffer, size, "value of %s is %s",
2477 name, value);
28f540f4 2478 @}
4cca6b86
UD
2479 /* @r{The last call worked, return the string.} */
2480 return buffer;
28f540f4
RM
2481@}
2482@end group
2483@end smallexample
2484
2485In practice, it is often easier just to use @code{asprintf}, below.
fb971363 2486
1f77f049 2487@strong{Attention:} In versions of @theglibc{} prior to 2.1 the
5a74e68a
UD
2488return value is the number of characters stored, not including the
2489terminating null; unless there was not enough space in @var{s} to
2490store the result in which case @code{-1} is returned. This was
2491changed in order to comply with the @w{ISO C99} standard.
28f540f4
RM
2492@end deftypefun
2493
2494@node Dynamic Output
2495@subsection Dynamically Allocating Formatted Output
2496
2497The functions in this section do formatted output and place the results
2498in dynamically allocated memory.
2499
28f540f4 2500@deftypefun int asprintf (char **@var{ptr}, const char *@var{template}, @dots{})
d08a7e4c 2501@standards{GNU, stdio.h}
171e9210 2502@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2503This function is similar to @code{sprintf}, except that it dynamically
2504allocates a string (as with @code{malloc}; @pxref{Unconstrained
2505Allocation}) to hold the output, instead of putting the output in a
2506buffer you allocate in advance. The @var{ptr} argument should be the
3a4e0609
UD
2507address of a @code{char *} object, and a successful call to
2508@code{asprintf} stores a pointer to the newly allocated string at that
2509location.
28f540f4 2510
7ba73c63 2511The return value is the number of characters allocated for the buffer, or
cf822e3c 2512less than zero if an error occurred. Usually this means that the buffer
7ba73c63
UD
2513could not be allocated.
2514
28f540f4
RM
2515Here is how to use @code{asprintf} to get the same result as the
2516@code{snprintf} example, but more easily:
2517
2518@smallexample
2519/* @r{Construct a message describing the value of a variable}
2520 @r{whose name is @var{name} and whose value is @var{value}.} */
2521char *
2522make_message (char *name, char *value)
2523@{
2524 char *result;
7ba73c63
UD
2525 if (asprintf (&result, "value of %s is %s", name, value) < 0)
2526 return NULL;
28f540f4
RM
2527 return result;
2528@}
2529@end smallexample
2530@end deftypefun
2531
28f540f4 2532@deftypefun int obstack_printf (struct obstack *@var{obstack}, const char *@var{template}, @dots{})
d08a7e4c 2533@standards{GNU, stdio.h}
171e9210 2534@safety{@prelim{}@mtsafe{@mtsrace{:obstack} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
28f540f4
RM
2535This function is similar to @code{asprintf}, except that it uses the
2536obstack @var{obstack} to allocate the space. @xref{Obstacks}.
2537
2538The characters are written onto the end of the current object.
2539To get at them, you must finish the object with @code{obstack_finish}
0005e54f 2540(@pxref{Growing Objects}).
28f540f4
RM
2541@end deftypefun
2542
2543@node Variable Arguments Output
2544@subsection Variable Arguments Output Functions
2545
2546The functions @code{vprintf} and friends are provided so that you can
2547define your own variadic @code{printf}-like functions that make use of
2548the same internals as the built-in formatted output functions.
2549
2550The most natural way to define such functions would be to use a language
2551construct to say, ``Call @code{printf} and pass this template plus all
2552of my arguments after the first five.'' But there is no way to do this
2553in C, and it would be hard to provide a way, since at the C language
2554level there is no way to tell how many arguments your function received.
2555
2556Since that method is impossible, we provide alternative functions, the
2557@code{vprintf} series, which lets you pass a @code{va_list} to describe
2558``all of my arguments after the first five.''
2559
19c3f208 2560When it is sufficient to define a macro rather than a real function,
28f540f4
RM
2561the GNU C compiler provides a way to do this much more easily with macros.
2562For example:
2563
2564@smallexample
838e5ffe 2565#define myprintf(a, b, c, d, e, rest...) \
162ba701 2566 printf (mytemplate , ## rest)
28f540f4
RM
2567@end smallexample
2568
2569@noindent
9229b83e
RM
2570@xref{Variadic Macros,,, cpp, The C preprocessor}, for details.
2571But this is limited to macros, and does not apply to real functions at all.
28f540f4
RM
2572
2573Before calling @code{vprintf} or the other functions listed in this
2574section, you @emph{must} call @code{va_start} (@pxref{Variadic
2575Functions}) to initialize a pointer to the variable arguments. Then you
2576can call @code{va_arg} to fetch the arguments that you want to handle
2577yourself. This advances the pointer past those arguments.
2578
2579Once your @code{va_list} pointer is pointing at the argument of your
2580choice, you are ready to call @code{vprintf}. That argument and all
2581subsequent arguments that were passed to your function are used by
2582@code{vprintf} along with the template that you specified separately.
2583
f546f87c
FW
2584@strong{Portability Note:} The value of the @code{va_list} pointer is
2585undetermined after the call to @code{vprintf}, so you must not use
2586@code{va_arg} after you call @code{vprintf}. Instead, you should call
2587@code{va_end} to retire the pointer from service. You can call
2588@code{va_start} again and begin fetching the arguments from the start of
2589the variable argument list. (Alternatively, you can use @code{va_copy}
2590to make a copy of the @code{va_list} pointer before calling
2591@code{vfprintf}.) Calling @code{vprintf} does not destroy the argument
2592list of your function, merely the particular pointer that you passed to
2593it.
28f540f4
RM
2594
2595Prototypes for these functions are declared in @file{stdio.h}.
2596@pindex stdio.h
2597
28f540f4 2598@deftypefun int vprintf (const char *@var{template}, va_list @var{ap})
d08a7e4c 2599@standards{ISO, stdio.h}
171e9210 2600@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
2601This function is similar to @code{printf} except that, instead of taking
2602a variable number of arguments directly, it takes an argument list
2603pointer @var{ap}.
2604@end deftypefun
2605
b5e73f56 2606@deftypefun int vwprintf (const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 2607@standards{ISO, wchar.h}
171e9210 2608@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
2609This function is similar to @code{wprintf} except that, instead of taking
2610a variable number of arguments directly, it takes an argument list
2611pointer @var{ap}.
2612@end deftypefun
2613
28f540f4 2614@deftypefun int vfprintf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
d08a7e4c 2615@standards{ISO, stdio.h}
171e9210
AO
2616@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
2617@c Although vfprintf sets up a cleanup region to release the lock on the
2618@c output stream, it doesn't use it to release args_value or string in
2619@c case of cancellation. This doesn't make it unsafe, but cancelling it
2620@c may leak memory. The unguarded use of __printf_function_table is
2621@c also of concern for all callers.
2622@c _itoa ok
2623@c _udiv_qrnnd_preinv ok
2624@c group_number ok
2625@c _i18n_number_rewrite
2626@c __wctrans ok
2627@c __towctrans @mtslocale
2628@c __wcrtomb ok? dup below
2629@c outdigit_value ok
2630@c outdigitwc_value ok
2631@c outchar ok
2632@c outstring ok
2633@c PAD ok
2634@c __printf_fp @mtslocale @ascuheap @acsmem
2635@c __printf_fphex @mtslocale
2636@c __readonly_area
2637@c [GNU/Linux] fopen, strtoul, free
2638@c __strerror_r ok if no translation, check otherwise
2639@c __btowc ? gconv-modules
2640@c __wcrtomb ok (not using internal state) gconv-modules
2641@c ARGCHECK
2642@c UNBUFFERED_P (tested before taking the stream lock)
2643@c buffered_vfprintf ok
2644@c __find_spec(wc|mb)
2645@c read_int
2646@c __libc_use_alloca
2647@c process_arg
2648@c process_string_arg
171e9210
AO
2649@c __parse_one_spec(wc|mb)
2650@c *__printf_arginfo_table unguarded
2651@c __printf_va_arg_table-> unguarded
2652@c *__printf_function_table unguarded
2653@c done_add
2654@c printf_unknown
2655@c outchar
2656@c _itoa_word
28f540f4
RM
2657This is the equivalent of @code{fprintf} with the variable argument list
2658specified directly as for @code{vprintf}.
2659@end deftypefun
2660
b5e73f56 2661@deftypefun int vfwprintf (FILE *@var{stream}, const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 2662@standards{ISO, wchar.h}
171e9210 2663@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
2664This is the equivalent of @code{fwprintf} with the variable argument list
2665specified directly as for @code{vwprintf}.
2666@end deftypefun
2667
28f540f4 2668@deftypefun int vsprintf (char *@var{s}, const char *@var{template}, va_list @var{ap})
d08a7e4c 2669@standards{ISO, stdio.h}
171e9210 2670@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2671This is the equivalent of @code{sprintf} with the variable argument list
2672specified directly as for @code{vprintf}.
2673@end deftypefun
2674
c703cd7a 2675@deftypefun int vswprintf (wchar_t *@var{ws}, size_t @var{size}, const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 2676@standards{GNU, wchar.h}
171e9210 2677@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b5e73f56
UD
2678This is the equivalent of @code{swprintf} with the variable argument list
2679specified directly as for @code{vwprintf}.
2680@end deftypefun
2681
28f540f4 2682@deftypefun int vsnprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, va_list @var{ap})
d08a7e4c 2683@standards{GNU, stdio.h}
171e9210 2684@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2685This is the equivalent of @code{snprintf} with the variable argument list
2686specified directly as for @code{vprintf}.
2687@end deftypefun
2688
28f540f4 2689@deftypefun int vasprintf (char **@var{ptr}, const char *@var{template}, va_list @var{ap})
d08a7e4c 2690@standards{GNU, stdio.h}
171e9210 2691@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
2692The @code{vasprintf} function is the equivalent of @code{asprintf} with the
2693variable argument list specified directly as for @code{vprintf}.
2694@end deftypefun
2695
28f540f4 2696@deftypefun int obstack_vprintf (struct obstack *@var{obstack}, const char *@var{template}, va_list @var{ap})
d08a7e4c 2697@standards{GNU, stdio.h}
171e9210
AO
2698@safety{@prelim{}@mtsafe{@mtsrace{:obstack} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acucorrupt{} @acsmem{}}}
2699@c The obstack is not guarded by mutexes, it might be at an inconsistent
2700@c state within a signal handler, and it could be left at an
2701@c inconsistent state in case of cancellation.
28f540f4
RM
2702The @code{obstack_vprintf} function is the equivalent of
2703@code{obstack_printf} with the variable argument list specified directly
0005e54f 2704as for @code{vprintf}.
28f540f4
RM
2705@end deftypefun
2706
2707Here's an example showing how you might use @code{vfprintf}. This is a
2708function that prints error messages to the stream @code{stderr}, along
2709with a prefix indicating the name of the program
19c3f208 2710(@pxref{Error Messages}, for a description of
28f540f4
RM
2711@code{program_invocation_short_name}).
2712
2713@smallexample
2714@group
2715#include <stdio.h>
2716#include <stdarg.h>
2717
2718void
2719eprintf (const char *template, ...)
2720@{
2721 va_list ap;
2722 extern char *program_invocation_short_name;
2723
2724 fprintf (stderr, "%s: ", program_invocation_short_name);
4b8f94d3 2725 va_start (ap, template);
28f540f4
RM
2726 vfprintf (stderr, template, ap);
2727 va_end (ap);
2728@}
2729@end group
2730@end smallexample
2731
2732@noindent
2733You could call @code{eprintf} like this:
2734
2735@smallexample
2736eprintf ("file `%s' does not exist\n", filename);
2737@end smallexample
2738
2739In GNU C, there is a special construct you can use to let the compiler
2740know that a function uses a @code{printf}-style format string. Then it
2741can check the number and types of arguments in each call to the
2742function, and warn you when they do not match the format string.
2743For example, take this declaration of @code{eprintf}:
2744
2745@smallexample
2746void eprintf (const char *template, ...)
162ba701 2747 __attribute__ ((format (printf, 1, 2)));
28f540f4
RM
2748@end smallexample
2749
2750@noindent
2751This tells the compiler that @code{eprintf} uses a format string like
2752@code{printf} (as opposed to @code{scanf}; @pxref{Formatted Input});
2753the format string appears as the first argument;
2754and the arguments to satisfy the format begin with the second.
2755@xref{Function Attributes, , Declaring Attributes of Functions,
1f6676d7 2756gcc, Using GNU CC}, for more information.
28f540f4
RM
2757
2758@node Parsing a Template String
2759@subsection Parsing a Template String
2760@cindex parsing a template string
2761
2762You can use the function @code{parse_printf_format} to obtain
2763information about the number and types of arguments that are expected by
2764a given template string. This function permits interpreters that
2765provide interfaces to @code{printf} to avoid passing along invalid
2766arguments from the user's program, which could cause a crash.
2767
2768All the symbols described in this section are declared in the header
2769file @file{printf.h}.
2770
28f540f4 2771@deftypefun size_t parse_printf_format (const char *@var{template}, size_t @var{n}, int *@var{argtypes})
d08a7e4c 2772@standards{GNU, printf.h}
171e9210 2773@safety{@prelim{}@mtsafe{@mtslocale{}}@assafe{}@acsafe{}}
28f540f4
RM
2774This function returns information about the number and types of
2775arguments expected by the @code{printf} template string @var{template}.
2776The information is stored in the array @var{argtypes}; each element of
2777this array describes one argument. This information is encoded using
2778the various @samp{PA_} macros, listed below.
2779
04b9968b
UD
2780The argument @var{n} specifies the number of elements in the array
2781@var{argtypes}. This is the maximum number of elements that
28f540f4
RM
2782@code{parse_printf_format} will try to write.
2783
2784@code{parse_printf_format} returns the total number of arguments required
2785by @var{template}. If this number is greater than @var{n}, then the
2786information returned describes only the first @var{n} arguments. If you
04b9968b 2787want information about additional arguments, allocate a bigger
28f540f4
RM
2788array and call @code{parse_printf_format} again.
2789@end deftypefun
2790
2791The argument types are encoded as a combination of a basic type and
2792modifier flag bits.
2793
28f540f4 2794@deftypevr Macro int PA_FLAG_MASK
d08a7e4c 2795@standards{GNU, printf.h}
28f540f4
RM
2796This macro is a bitmask for the type modifier flag bits. You can write
2797the expression @code{(argtypes[i] & PA_FLAG_MASK)} to extract just the
2798flag bits for an argument, or @code{(argtypes[i] & ~PA_FLAG_MASK)} to
2799extract just the basic type code.
2800@end deftypevr
2801
2802Here are symbolic constants that represent the basic types; they stand
2803for integer values.
2804
779ae82e 2805@vtable @code
28f540f4 2806@item PA_INT
d08a7e4c 2807@standards{GNU, printf.h}
28f540f4
RM
2808This specifies that the base type is @code{int}.
2809
28f540f4 2810@item PA_CHAR
d08a7e4c 2811@standards{GNU, printf.h}
28f540f4
RM
2812This specifies that the base type is @code{int}, cast to @code{char}.
2813
28f540f4 2814@item PA_STRING
d08a7e4c 2815@standards{GNU, printf.h}
28f540f4
RM
2816This specifies that the base type is @code{char *}, a null-terminated string.
2817
28f540f4 2818@item PA_POINTER
d08a7e4c 2819@standards{GNU, printf.h}
28f540f4
RM
2820This specifies that the base type is @code{void *}, an arbitrary pointer.
2821
28f540f4 2822@item PA_FLOAT
d08a7e4c 2823@standards{GNU, printf.h}
28f540f4
RM
2824This specifies that the base type is @code{float}.
2825
28f540f4 2826@item PA_DOUBLE
d08a7e4c 2827@standards{GNU, printf.h}
28f540f4
RM
2828This specifies that the base type is @code{double}.
2829
28f540f4 2830@item PA_LAST
d08a7e4c 2831@standards{GNU, printf.h}
28f540f4
RM
2832You can define additional base types for your own programs as offsets
2833from @code{PA_LAST}. For example, if you have data types @samp{foo}
2834and @samp{bar} with their own specialized @code{printf} conversions,
2835you could define encodings for these types as:
2836
2837@smallexample
2838#define PA_FOO PA_LAST
2839#define PA_BAR (PA_LAST + 1)
2840@end smallexample
779ae82e 2841@end vtable
28f540f4
RM
2842
2843Here are the flag bits that modify a basic type. They are combined with
2844the code for the basic type using inclusive-or.
2845
779ae82e 2846@vtable @code
28f540f4 2847@item PA_FLAG_PTR
d08a7e4c 2848@standards{GNU, printf.h}
28f540f4
RM
2849If this bit is set, it indicates that the encoded type is a pointer to
2850the base type, rather than an immediate value.
2851For example, @samp{PA_INT|PA_FLAG_PTR} represents the type @samp{int *}.
2852
28f540f4 2853@item PA_FLAG_SHORT
d08a7e4c 2854@standards{GNU, printf.h}
28f540f4
RM
2855If this bit is set, it indicates that the base type is modified with
2856@code{short}. (This corresponds to the @samp{h} type modifier.)
2857
28f540f4 2858@item PA_FLAG_LONG
d08a7e4c 2859@standards{GNU, printf.h}
28f540f4
RM
2860If this bit is set, it indicates that the base type is modified with
2861@code{long}. (This corresponds to the @samp{l} type modifier.)
2862
28f540f4 2863@item PA_FLAG_LONG_LONG
d08a7e4c 2864@standards{GNU, printf.h}
28f540f4
RM
2865If this bit is set, it indicates that the base type is modified with
2866@code{long long}. (This corresponds to the @samp{L} type modifier.)
2867
28f540f4 2868@item PA_FLAG_LONG_DOUBLE
d08a7e4c 2869@standards{GNU, printf.h}
28f540f4
RM
2870This is a synonym for @code{PA_FLAG_LONG_LONG}, used by convention with
2871a base type of @code{PA_DOUBLE} to indicate a type of @code{long double}.
779ae82e 2872@end vtable
28f540f4
RM
2873
2874@ifinfo
6d52618b 2875For an example of using these facilities, see @ref{Example of Parsing}.
28f540f4
RM
2876@end ifinfo
2877
2878@node Example of Parsing
2879@subsection Example of Parsing a Template String
2880
2881Here is an example of decoding argument types for a format string. We
2882assume this is part of an interpreter which contains arguments of type
2883@code{NUMBER}, @code{CHAR}, @code{STRING} and @code{STRUCTURE} (and
2884perhaps others which are not valid here).
2885
2886@smallexample
2887/* @r{Test whether the @var{nargs} specified objects}
2888 @r{in the vector @var{args} are valid}
2889 @r{for the format string @var{format}:}
2890 @r{if so, return 1.}
2891 @r{If not, return 0 after printing an error message.} */
2892
2893int
2894validate_args (char *format, int nargs, OBJECT *args)
2895@{
2896 int *argtypes;
2897 int nwanted;
2898
2899 /* @r{Get the information about the arguments.}
2900 @r{Each conversion specification must be at least two characters}
2901 @r{long, so there cannot be more specifications than half the}
2902 @r{length of the string.} */
2903
2904 argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
72bcc9ad 2905 nwanted = parse_printf_format (format, nargs, argtypes);
28f540f4
RM
2906
2907 /* @r{Check the number of arguments.} */
2908 if (nwanted > nargs)
2909 @{
2910 error ("too few arguments (at least %d required)", nwanted);
2911 return 0;
2912 @}
19c3f208 2913
28f540f4
RM
2914 /* @r{Check the C type wanted for each argument}
2915 @r{and see if the object given is suitable.} */
2916 for (i = 0; i < nwanted; i++)
2917 @{
2918 int wanted;
2919
2920 if (argtypes[i] & PA_FLAG_PTR)
162ba701 2921 wanted = STRUCTURE;
28f540f4 2922 else
162ba701
PIM
2923 switch (argtypes[i] & ~PA_FLAG_MASK)
2924 @{
2925 case PA_INT:
2926 case PA_FLOAT:
2927 case PA_DOUBLE:
2928 wanted = NUMBER;
2929 break;
2930 case PA_CHAR:
2931 wanted = CHAR;
2932 break;
2933 case PA_STRING:
2934 wanted = STRING;
2935 break;
2936 case PA_POINTER:
2937 wanted = STRUCTURE;
2938 break;
2939 @}
28f540f4 2940 if (TYPE (args[i]) != wanted)
162ba701
PIM
2941 @{
2942 error ("type mismatch for arg number %d", i);
2943 return 0;
2944 @}
28f540f4
RM
2945 @}
2946 return 1;
2947@}
2948@end smallexample
2949
2950@node Customizing Printf
2951@section Customizing @code{printf}
2952@cindex customizing @code{printf}
2953@cindex defining new @code{printf} conversions
2954@cindex extending @code{printf}
2955
1f77f049 2956@Theglibc{} lets you define your own custom conversion specifiers
28f540f4
RM
2957for @code{printf} template strings, to teach @code{printf} clever ways
2958to print the important data structures of your program.
2959
2960The way you do this is by registering the conversion with the function
2961@code{register_printf_function}; see @ref{Registering New Conversions}.
2962One of the arguments you pass to this function is a pointer to a handler
2963function that produces the actual output; see @ref{Defining the Output
2964Handler}, for information on how to write this function.
2965
2966You can also install a function that just returns information about the
2967number and type of arguments expected by the conversion specifier.
2968@xref{Parsing a Template String}, for information about this.
2969
2970The facilities of this section are declared in the header file
2971@file{printf.h}.
2972
2973@menu
19c3f208 2974* Registering New Conversions:: Using @code{register_printf_function}
162ba701 2975 to register a new output conversion.
28f540f4 2976* Conversion Specifier Options:: The handler must be able to get
162ba701
PIM
2977 the options specified in the
2978 template when it is called.
28f540f4 2979* Defining the Output Handler:: Defining the handler and arginfo
162ba701
PIM
2980 functions that are passed as arguments
2981 to @code{register_printf_function}.
28f540f4 2982* Printf Extension Example:: How to define a @code{printf}
162ba701 2983 handler function.
29bb8719 2984* Predefined Printf Handlers:: Predefined @code{printf} handlers.
28f540f4
RM
2985@end menu
2986
2987@strong{Portability Note:} The ability to extend the syntax of
f65fd747 2988@code{printf} template strings is a GNU extension. ISO standard C has
7e8989d0
MS
2989nothing similar. When using the GNU C compiler or any other compiler
2990that interprets calls to standard I/O functions according to the rules
2991of the language standard it is necessary to disable such handling by
2992the appropriate compiler option. Otherwise the behavior of a program
2993that relies on the extension is undefined.
28f540f4
RM
2994
2995@node Registering New Conversions
2996@subsection Registering New Conversions
2997
2998The function to register a new output conversion is
2999@code{register_printf_function}, declared in @file{printf.h}.
3000@pindex printf.h
3001
28f540f4 3002@deftypefun int register_printf_function (int @var{spec}, printf_function @var{handler-function}, printf_arginfo_function @var{arginfo-function})
d08a7e4c 3003@standards{GNU, printf.h}
171e9210
AO
3004@safety{@prelim{}@mtunsafe{@mtasuconst{:printfext}}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
3005@c This function is guarded by the global non-recursive libc lock, but
3006@c users of the variables it sets aren't, and those should be MT-Safe,
3007@c so we're ruling out the use of this extension with threads. Calling
3008@c it from a signal handler may self-deadlock, and cancellation may
3009@c leave the lock held, besides leaking allocated memory.
28f540f4 3010This function defines the conversion specifier character @var{spec}.
42be70d4 3011Thus, if @var{spec} is @code{'Y'}, it defines the conversion @samp{%Y}.
28f540f4
RM
3012You can redefine the built-in conversions like @samp{%s}, but flag
3013characters like @samp{#} and type modifiers like @samp{l} can never be
3014used as conversions; calling @code{register_printf_function} for those
42be70d4
UD
3015characters has no effect. It is advisable not to use lowercase letters,
3016since the ISO C standard warns that additional lowercase letters may be
3017standardized in future editions of the standard.
28f540f4
RM
3018
3019The @var{handler-function} is the function called by @code{printf} and
3020friends when this conversion appears in a template string.
3021@xref{Defining the Output Handler}, for information about how to define
3022a function to pass as this argument. If you specify a null pointer, any
3023existing handler function for @var{spec} is removed.
3024
3025The @var{arginfo-function} is the function called by
3026@code{parse_printf_format} when this conversion appears in a
3027template string. @xref{Parsing a Template String}, for information
3028about this.
3029
54d79e99
UD
3030@c The following is not true anymore. The `parse_printf_format' function
3031@c is now also called from `vfprintf' via `parse_one_spec'.
3032@c --drepper@gnu, 1996/11/14
3033@c
3034@c Normally, you install both functions for a conversion at the same time,
3035@c but if you are never going to call @code{parse_printf_format}, you do
3036@c not need to define an arginfo function.
3037
1f77f049 3038@strong{Attention:} In @theglibc{} versions before 2.0 the
54d79e99 3039@var{arginfo-function} function did not need to be installed unless
04b9968b 3040the user used the @code{parse_printf_format} function. This has changed.
54d79e99
UD
3041Now a call to any of the @code{printf} functions will call this
3042function when this format specifier appears in the format string.
28f540f4
RM
3043
3044The return value is @code{0} on success, and @code{-1} on failure
3045(which occurs if @var{spec} is out of range).
3046
7e8989d0
MS
3047@strong{Portability Note:} It is possible to redefine the standard output
3048conversions but doing so is strongly discouraged because it may interfere
3049with the behavior of programs and compiler implementations that assume
3050the effects of the conversions conform to the relevant language standards.
3051In addition, conforming compilers need not guarantee that the function
3052registered for a standard conversion will be called for each such
3053conversion in every format string in a program.
28f540f4
RM
3054@end deftypefun
3055
3056@node Conversion Specifier Options
3057@subsection Conversion Specifier Options
3058
40deae08
RM
3059If you define a meaning for @samp{%A}, what if the template contains
3060@samp{%+23A} or @samp{%-#A}? To implement a sensible meaning for these,
28f540f4
RM
3061the handler when called needs to be able to get the options specified in
3062the template.
3063
838e5ffe
UD
3064Both the @var{handler-function} and @var{arginfo-function} accept an
3065argument that points to a @code{struct printf_info}, which contains
3066information about the options appearing in an instance of the conversion
3067specifier. This data type is declared in the header file
3068@file{printf.h}.
28f540f4
RM
3069@pindex printf.h
3070
28f540f4 3071@deftp {Type} {struct printf_info}
d08a7e4c 3072@standards{GNU, printf.h}
28f540f4
RM
3073This structure is used to pass information about the options appearing
3074in an instance of a conversion specifier in a @code{printf} template
3075string to the handler and arginfo functions for that specifier. It
3076contains the following members:
3077
3078@table @code
3079@item int prec
3080This is the precision specified. The value is @code{-1} if no precision
3081was specified. If the precision was given as @samp{*}, the
3082@code{printf_info} structure passed to the handler function contains the
3083actual value retrieved from the argument list. But the structure passed
3084to the arginfo function contains a value of @code{INT_MIN}, since the
3085actual value is not known.
3086
3087@item int width
3088This is the minimum field width specified. The value is @code{0} if no
3089width was specified. If the field width was given as @samp{*}, the
3090@code{printf_info} structure passed to the handler function contains the
3091actual value retrieved from the argument list. But the structure passed
3092to the arginfo function contains a value of @code{INT_MIN}, since the
3093actual value is not known.
3094
54d79e99 3095@item wchar_t spec
28f540f4
RM
3096This is the conversion specifier character specified. It's stored in
3097the structure so that you can register the same handler function for
3098multiple characters, but still have a way to tell them apart when the
3099handler function is called.
3100
3101@item unsigned int is_long_double
3102This is a boolean that is true if the @samp{L}, @samp{ll}, or @samp{q}
3103type modifier was specified. For integer conversions, this indicates
3104@code{long long int}, as opposed to @code{long double} for floating
3105point conversions.
3106
d64b6ad0
UD
3107@item unsigned int is_char
3108This is a boolean that is true if the @samp{hh} type modifier was specified.
3109
28f540f4
RM
3110@item unsigned int is_short
3111This is a boolean that is true if the @samp{h} type modifier was specified.
3112
3113@item unsigned int is_long
3114This is a boolean that is true if the @samp{l} type modifier was specified.
3115
3116@item unsigned int alt
3117This is a boolean that is true if the @samp{#} flag was specified.
3118
3119@item unsigned int space
3120This is a boolean that is true if the @samp{ } flag was specified.
3121
3122@item unsigned int left
3123This is a boolean that is true if the @samp{-} flag was specified.
3124
3125@item unsigned int showsign
3126This is a boolean that is true if the @samp{+} flag was specified.
3127
3128@item unsigned int group
3129This is a boolean that is true if the @samp{'} flag was specified.
3130
54d79e99
UD
3131@item unsigned int extra
3132This flag has a special meaning depending on the context. It could
3133be used freely by the user-defined handlers but when called from
3134the @code{printf} function this variable always contains the value
3135@code{0}.
3136
d64b6ad0
UD
3137@item unsigned int wide
3138This flag is set if the stream is wide oriented.
3139
54d79e99 3140@item wchar_t pad
28f540f4
RM
3141This is the character to use for padding the output to the minimum field
3142width. The value is @code{'0'} if the @samp{0} flag was specified, and
3143@code{' '} otherwise.
3144@end table
3145@end deftp
3146
3147
3148@node Defining the Output Handler
3149@subsection Defining the Output Handler
3150
3151Now let's look at how to define the handler and arginfo functions
3152which are passed as arguments to @code{register_printf_function}.
3153
1f77f049 3154@strong{Compatibility Note:} The interface changed in @theglibc{}
54d79e99
UD
3155version 2.0. Previously the third argument was of type
3156@code{va_list *}.
3157
28f540f4
RM
3158You should define your handler functions with a prototype like:
3159
3160@smallexample
3161int @var{function} (FILE *stream, const struct printf_info *info,
162ba701 3162 const void *const *args)
28f540f4
RM
3163@end smallexample
3164
54d79e99 3165The @var{stream} argument passed to the handler function is the stream to
28f540f4
RM
3166which it should write output.
3167
54d79e99 3168The @var{info} argument is a pointer to a structure that contains
28f540f4
RM
3169information about the various options that were included with the
3170conversion in the template string. You should not modify this structure
3171inside your handler function. @xref{Conversion Specifier Options}, for
3172a description of this data structure.
3173
54d79e99
UD
3174@c The following changes some time back. --drepper@gnu, 1996/11/14
3175@c
3176@c The @code{ap_pointer} argument is used to pass the tail of the variable
3177@c argument list containing the values to be printed to your handler.
3178@c Unlike most other functions that can be passed an explicit variable
3179@c argument list, this is a @emph{pointer} to a @code{va_list}, rather than
3180@c the @code{va_list} itself. Thus, you should fetch arguments by
3181@c means of @code{va_arg (*ap_pointer, @var{type})}.
3182@c
3183@c (Passing a pointer here allows the function that calls your handler
3184@c function to update its own @code{va_list} variable to account for the
3185@c arguments that your handler processes. @xref{Variadic Functions}.)
3186
3187The @var{args} is a vector of pointers to the arguments data.
04b9968b 3188The number of arguments was determined by calling the argument
54d79e99 3189information function provided by the user.
28f540f4
RM
3190
3191Your handler function should return a value just like @code{printf}
3192does: it should return the number of characters it has written, or a
3193negative value to indicate an error.
3194
28f540f4 3195@deftp {Data Type} printf_function
d08a7e4c 3196@standards{GNU, printf.h}
28f540f4
RM
3197This is the data type that a handler function should have.
3198@end deftp
3199
3200If you are going to use @w{@code{parse_printf_format}} in your
54d79e99 3201application, you must also define a function to pass as the
28f540f4 3202@var{arginfo-function} argument for each new conversion you install with
19c3f208 3203@code{register_printf_function}.
28f540f4 3204
54d79e99 3205You have to define these functions with a prototype like:
28f540f4
RM
3206
3207@smallexample
3208int @var{function} (const struct printf_info *info,
162ba701 3209 size_t n, int *argtypes)
28f540f4
RM
3210@end smallexample
3211
3212The return value from the function should be the number of arguments the
3213conversion expects. The function should also fill in no more than
3214@var{n} elements of the @var{argtypes} array with information about the
3215types of each of these arguments. This information is encoded using the
3216various @samp{PA_} macros. (You will notice that this is the same
3217calling convention @code{parse_printf_format} itself uses.)
3218
28f540f4 3219@deftp {Data Type} printf_arginfo_function
d08a7e4c 3220@standards{GNU, printf.h}
28f540f4
RM
3221This type is used to describe functions that return information about
3222the number and type of arguments used by a conversion specifier.
3223@end deftp
3224
3225@node Printf Extension Example
3226@subsection @code{printf} Extension Example
3227
3228Here is an example showing how to define a @code{printf} handler function.
19c3f208 3229This program defines a data structure called a @code{Widget} and
28f540f4
RM
3230defines the @samp{%W} conversion to print information about @w{@code{Widget *}}
3231arguments, including the pointer value and the name stored in the data
3232structure. The @samp{%W} conversion supports the minimum field width and
3233left-justification options, but ignores everything else.
3234
3235@smallexample
3236@include rprintf.c.texi
3237@end smallexample
3238
3239The output produced by this program looks like:
3240
3241@smallexample
3242|<Widget 0xffeffb7c: mywidget>|
3243| <Widget 0xffeffb7c: mywidget>|
3244|<Widget 0xffeffb7c: mywidget> |
3245@end smallexample
3246
29bb8719
UD
3247@node Predefined Printf Handlers
3248@subsection Predefined @code{printf} Handlers
3249
1f77f049 3250@Theglibc{} also contains a concrete and useful application of the
29bb8719
UD
3251@code{printf} handler extension. There are two functions available
3252which implement a special way to print floating-point numbers.
3253
29bb8719 3254@deftypefun int printf_size (FILE *@var{fp}, const struct printf_info *@var{info}, const void *const *@var{args})
d08a7e4c 3255@standards{GNU, printf.h}
171e9210
AO
3256@safety{@prelim{}@mtsafe{@mtsrace{:fp} @mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @acucorrupt{}}}
3257@c This is meant to be called by vfprintf, that should hold the lock on
3258@c the stream, but if this function is called directly, output will be
3259@c racy, besides the uses of the global locale object while other
3260@c threads may be changing it and the possbility of leaving the stream
3261@c object in an inconsistent state in case of cancellation.
29bb8719
UD
3262Print a given floating point number as for the format @code{%f} except
3263that there is a postfix character indicating the divisor for the
3264number to make this less than 1000. There are two possible divisors:
04b9968b 3265powers of 1024 or powers of 1000. Which one is used depends on the
29bb8719
UD
3266format character specified while registered this handler. If the
3267character is of lower case, 1024 is used. For upper case characters,
32681000 is used.
3269
3270The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes,
3271etc. The full table is:
3272
779ae82e 3273@ifinfo
029264d1 3274@multitable {' '} {2^10 (1024)} {zetta} {Upper} {10^24 (1000)}
29bb8719
UD
3275@item low @tab Multiplier @tab From @tab Upper @tab Multiplier
3276@item ' ' @tab 1 @tab @tab ' ' @tab 1
3277@item k @tab 2^10 (1024) @tab kilo @tab K @tab 10^3 (1000)
3278@item m @tab 2^20 @tab mega @tab M @tab 10^6
3279@item g @tab 2^30 @tab giga @tab G @tab 10^9
3280@item t @tab 2^40 @tab tera @tab T @tab 10^12
3281@item p @tab 2^50 @tab peta @tab P @tab 10^15
3282@item e @tab 2^60 @tab exa @tab E @tab 10^18
3283@item z @tab 2^70 @tab zetta @tab Z @tab 10^21
3284@item y @tab 2^80 @tab yotta @tab Y @tab 10^24
3285@end multitable
779ae82e
UD
3286@end ifinfo
3287@iftex
3288@tex
3289\hbox to\hsize{\hfil\vbox{\offinterlineskip
3290\hrule
3291\halign{\strut#& \vrule#\tabskip=1em plus2em& {\tt#}\hfil& \vrule#& #\hfil& \vrule#& #\hfil& \vrule#& {\tt#}\hfil& \vrule#& #\hfil& \vrule#\tabskip=0pt\cr
3292\noalign{\hrule}
3293\omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
3294&& \omit low && Multiplier && From && \omit Upper && Multiplier &\cr
3295\omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
3296\noalign{\hrule}
3297&& {\tt\char32} && 1 && && {\tt\char32} && 1 &\cr
3298&& k && $2^{10} = 1024$ && kilo && K && $10^3 = 1000$ &\cr
3299&& m && $2^{20}$ && mega && M && $10^6$ &\cr
3300&& g && $2^{30}$ && giga && G && $10^9$ &\cr
3301&& t && $2^{40}$ && tera && T && $10^{12}$ &\cr
3302&& p && $2^{50}$ && peta && P && $10^{15}$ &\cr
3303&& e && $2^{60}$ && exa && E && $10^{18}$ &\cr
3304&& z && $2^{70}$ && zetta && Z && $10^{21}$ &\cr
3305&& y && $2^{80}$ && yotta && Y && $10^{24}$ &\cr
3306\noalign{\hrule}}}\hfil}
3307@end tex
3308@end iftex
29bb8719
UD
3309
3310The default precision is 3, i.e., 1024 is printed with a lower-case
3311format character as if it were @code{%.3fk} and will yield @code{1.000k}.
3312@end deftypefun
3313
3314Due to the requirements of @code{register_printf_function} we must also
04b9968b 3315provide the function which returns information about the arguments.
29bb8719 3316
29bb8719 3317@deftypefun int printf_size_info (const struct printf_info *@var{info}, size_t @var{n}, int *@var{argtypes})
d08a7e4c 3318@standards{GNU, printf.h}
171e9210 3319@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
29bb8719
UD
3320This function will return in @var{argtypes} the information about the
3321used parameters in the way the @code{vfprintf} implementation expects
3322it. The format always takes one argument.
3323@end deftypefun
3324
3325To use these functions both functions must be registered with a call like
3326
3327@smallexample
3328register_printf_function ('B', printf_size, printf_size_info);
3329@end smallexample
3330
3331Here we register the functions to print numbers as powers of 1000 since
f2ea0f5b 3332the format character @code{'B'} is an upper-case character. If we
29bb8719
UD
3333would additionally use @code{'b'} in a line like
3334
3335@smallexample
3336register_printf_function ('b', printf_size, printf_size_info);
3337@end smallexample
3338
3339@noindent
04b9968b
UD
3340we could also print using a power of 1024. Please note that all that is
3341different in these two lines is the format specifier. The
3342@code{printf_size} function knows about the difference between lower and upper
29bb8719
UD
3343case format specifiers.
3344
3345The use of @code{'B'} and @code{'b'} is no coincidence. Rather it is
3346the preferred way to use this functionality since it is available on
04b9968b 3347some other systems which also use format specifiers.
29bb8719 3348
28f540f4
RM
3349@node Formatted Input
3350@section Formatted Input
3351
3352@cindex formatted input from a stream
3353@cindex reading from a stream, formatted
3354@cindex format string, for @code{scanf}
3355@cindex template, for @code{scanf}
3356The functions described in this section (@code{scanf} and related
3357functions) provide facilities for formatted input analogous to the
3358formatted output facilities. These functions provide a mechanism for
3359reading arbitrary values under the control of a @dfn{format string} or
3360@dfn{template string}.
3361
3362@menu
3363* Formatted Input Basics:: Some basics to get you started.
3364* Input Conversion Syntax:: Syntax of conversion specifications.
3365* Table of Input Conversions:: Summary of input conversions and what they do.
3366* Numeric Input Conversions:: Details of conversions for reading numbers.
3367* String Input Conversions:: Details of conversions for reading strings.
3368* Dynamic String Input:: String conversions that @code{malloc} the buffer.
3369* Other Input Conversions:: Details of miscellaneous other conversions.
3370* Formatted Input Functions:: Descriptions of the actual functions.
3371* Variable Arguments Input:: @code{vscanf} and friends.
3372@end menu
3373
3374@node Formatted Input Basics
3375@subsection Formatted Input Basics
3376
3377Calls to @code{scanf} are superficially similar to calls to
3378@code{printf} in that arbitrary arguments are read under the control of
3379a template string. While the syntax of the conversion specifications in
3380the template is very similar to that for @code{printf}, the
3381interpretation of the template is oriented more towards free-format
3382input and simple pattern matching, rather than fixed-field formatting.
3383For example, most @code{scanf} conversions skip over any amount of
3384``white space'' (including spaces, tabs, and newlines) in the input
3385file, and there is no concept of precision for the numeric input
3386conversions as there is for the corresponding output conversions.
3387Ordinarily, non-whitespace characters in the template are expected to
3388match characters in the input stream exactly, but a matching failure is
3389distinct from an input error on the stream.
3390@cindex conversion specifications (@code{scanf})
3391
3392Another area of difference between @code{scanf} and @code{printf} is
3393that you must remember to supply pointers rather than immediate values
3394as the optional arguments to @code{scanf}; the values that are read are
3395stored in the objects that the pointers point to. Even experienced
3396programmers tend to forget this occasionally, so if your program is
3397getting strange errors that seem to be related to @code{scanf}, you
3398might want to double-check this.
3399
3400When a @dfn{matching failure} occurs, @code{scanf} returns immediately,
3401leaving the first non-matching character as the next character to be
3402read from the stream. The normal return value from @code{scanf} is the
3403number of values that were assigned, so you can use this to determine if
3404a matching error happened before all the expected values were read.
3405@cindex matching failure, in @code{scanf}
3406
3407The @code{scanf} function is typically used for things like reading in
3408the contents of tables. For example, here is a function that uses
3409@code{scanf} to initialize an array of @code{double}:
3410
3411@smallexample
3412void
3413readarray (double *array, int n)
3414@{
3415 int i;
3416 for (i=0; i<n; i++)
3417 if (scanf (" %lf", &(array[i])) != 1)
3418 invalid_input_error ();
3419@}
3420@end smallexample
3421
3422The formatted input functions are not used as frequently as the
3423formatted output functions. Partly, this is because it takes some care
3424to use them properly. Another reason is that it is difficult to recover
3425from a matching error.
3426
3427If you are trying to read input that doesn't match a single, fixed
3428pattern, you may be better off using a tool such as Flex to generate a
3429lexical scanner, or Bison to generate a parser, rather than using
9f508673
UD
3430@code{scanf}. For more information about these tools, see @ref{Top, , ,
3431flex.info, Flex: The Lexical Scanner Generator}, and @ref{Top, , ,
28f540f4
RM
3432bison.info, The Bison Reference Manual}.
3433
3434@node Input Conversion Syntax
3435@subsection Input Conversion Syntax
3436
3437A @code{scanf} template string is a string that contains ordinary
3438multibyte characters interspersed with conversion specifications that
3439start with @samp{%}.
3440
3441Any whitespace character (as defined by the @code{isspace} function;
3442@pxref{Classification of Characters}) in the template causes any number
3443of whitespace characters in the input stream to be read and discarded.
3444The whitespace characters that are matched need not be exactly the same
3445whitespace characters that appear in the template string. For example,
3446write @samp{ , } in the template to recognize a comma with optional
3447whitespace before and after.
3448
3449Other characters in the template string that are not part of conversion
3450specifications must match characters in the input stream exactly; if
3451this is not the case, a matching failure occurs.
3452
3453The conversion specifications in a @code{scanf} template string
3454have the general form:
3455
3456@smallexample
3457% @var{flags} @var{width} @var{type} @var{conversion}
3458@end smallexample
3459
3460In more detail, an input conversion specification consists of an initial
3461@samp{%} character followed in sequence by:
3462
3463@itemize @bullet
3464@item
3465An optional @dfn{flag character} @samp{*}, which says to ignore the text
3466read for this specification. When @code{scanf} finds a conversion
3467specification that uses this flag, it reads input as directed by the
3468rest of the conversion specification, but it discards this input, does
3469not use a pointer argument, and does not increment the count of
3470successful assignments.
3471@cindex flag character (@code{scanf})
3472
3473@item
3474An optional flag character @samp{a} (valid with string conversions only)
3475which requests allocation of a buffer long enough to store the string in.
3476(This is a GNU extension.)
3477@xref{Dynamic String Input}.
3478
3479@item
3480An optional decimal integer that specifies the @dfn{maximum field
3481width}. Reading of characters from the input stream stops either when
3482this maximum is reached or when a non-matching character is found,
3483whichever happens first. Most conversions discard initial whitespace
3484characters (those that don't are explicitly documented), and these
3485discarded characters don't count towards the maximum field width.
3486String input conversions store a null character to mark the end of the
3487input; the maximum field width does not include this terminator.
3488@cindex maximum field width (@code{scanf})
3489
3490@item
3491An optional @dfn{type modifier character}. For example, you can
3492specify a type modifier of @samp{l} with integer conversions such as
3493@samp{%d} to specify that the argument is a pointer to a @code{long int}
3494rather than a pointer to an @code{int}.
3495@cindex type modifier character (@code{scanf})
3496
3497@item
3498A character that specifies the conversion to be applied.
3499@end itemize
3500
19c3f208 3501The exact options that are permitted and how they are interpreted vary
28f540f4
RM
3502between the different conversion specifiers. See the descriptions of the
3503individual conversions for information about the particular options that
3504they allow.
3505
3506With the @samp{-Wformat} option, the GNU C compiler checks calls to
3507@code{scanf} and related functions. It examines the format string and
3508verifies that the correct number and types of arguments are supplied.
3509There is also a GNU C syntax to tell the compiler that a function you
19c3f208 3510write uses a @code{scanf}-style format string.
28f540f4 3511@xref{Function Attributes, , Declaring Attributes of Functions,
1f6676d7 3512gcc, Using GNU CC}, for more information.
28f540f4
RM
3513
3514@node Table of Input Conversions
3515@subsection Table of Input Conversions
3516@cindex input conversions, for @code{scanf}
3517
3518Here is a table that summarizes the various conversion specifications:
3519
3520@table @asis
3521@item @samp{%d}
3522Matches an optionally signed integer written in decimal. @xref{Numeric
3523Input Conversions}.
3524
3525@item @samp{%i}
3526Matches an optionally signed integer in any of the formats that the C
3527language defines for specifying an integer constant. @xref{Numeric
3528Input Conversions}.
3529
3530@item @samp{%o}
3531Matches an unsigned integer written in octal radix.
3532@xref{Numeric Input Conversions}.
3533
3534@item @samp{%u}
3535Matches an unsigned integer written in decimal radix.
3536@xref{Numeric Input Conversions}.
3537
3538@item @samp{%x}, @samp{%X}
3539Matches an unsigned integer written in hexadecimal radix.
3540@xref{Numeric Input Conversions}.
3541
0674613e 3542@item @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%F}, @samp{%G}
28f540f4
RM
3543Matches an optionally signed floating-point number. @xref{Numeric Input
3544Conversions}.
3545
3546@item @samp{%s}
b5e73f56 3547
28f540f4 3548Matches a string containing only non-whitespace characters.
b5e73f56
UD
3549@xref{String Input Conversions}. The presence of the @samp{l} modifier
3550determines whether the output is stored as a wide character string or a
3551multibyte string. If @samp{%s} is used in a wide character function the
3552string is converted as with multiple calls to @code{wcrtomb} into a
3553multibyte string. This means that the buffer must provide room for
3554@code{MB_CUR_MAX} bytes for each wide character read. In case
3555@samp{%ls} is used in a multibyte function the result is converted into
3556wide characters as with multiple calls of @code{mbrtowc} before being
3557stored in the user provided buffer.
3558
3559@item @samp{%S}
3560This is an alias for @samp{%ls} which is supported for compatibility
3561with the Unix standard.
28f540f4
RM
3562
3563@item @samp{%[}
3564Matches a string of characters that belong to a specified set.
b5e73f56
UD
3565@xref{String Input Conversions}. The presence of the @samp{l} modifier
3566determines whether the output is stored as a wide character string or a
3567multibyte string. If @samp{%[} is used in a wide character function the
3568string is converted as with multiple calls to @code{wcrtomb} into a
3569multibyte string. This means that the buffer must provide room for
3570@code{MB_CUR_MAX} bytes for each wide character read. In case
3571@samp{%l[} is used in a multibyte function the result is converted into
3572wide characters as with multiple calls of @code{mbrtowc} before being
3573stored in the user provided buffer.
28f540f4
RM
3574
3575@item @samp{%c}
3576Matches a string of one or more characters; the number of characters
3577read is controlled by the maximum field width given for the conversion.
3578@xref{String Input Conversions}.
3579
c703cd7a 3580If @samp{%c} is used in a wide stream function the read value is
b5e73f56
UD
3581converted from a wide character to the corresponding multibyte character
3582before storing it. Note that this conversion can produce more than one
c703cd7a 3583byte of output and therefore the provided buffer must be large enough for up
b5e73f56
UD
3584to @code{MB_CUR_MAX} bytes for each character. If @samp{%lc} is used in
3585a multibyte function the input is treated as a multibyte sequence (and
3586not bytes) and the result is converted as with calls to @code{mbrtowc}.
3587
3588@item @samp{%C}
3589This is an alias for @samp{%lc} which is supported for compatibility
3590with the Unix standard.
3591
28f540f4
RM
3592@item @samp{%p}
3593Matches a pointer value in the same implementation-defined format used
3594by the @samp{%p} output conversion for @code{printf}. @xref{Other Input
3595Conversions}.
3596
3597@item @samp{%n}
3598This conversion doesn't read any characters; it records the number of
3599characters read so far by this call. @xref{Other Input Conversions}.
3600
3601@item @samp{%%}
3602This matches a literal @samp{%} character in the input stream. No
3603corresponding argument is used. @xref{Other Input Conversions}.
3604@end table
3605
3606If the syntax of a conversion specification is invalid, the behavior is
3607undefined. If there aren't enough function arguments provided to supply
3608addresses for all the conversion specifications in the template strings
3609that perform assignments, or if the arguments are not of the correct
3610types, the behavior is also undefined. On the other hand, extra
3611arguments are simply ignored.
3612
3613@node Numeric Input Conversions
3614@subsection Numeric Input Conversions
3615
3616This section describes the @code{scanf} conversions for reading numeric
3617values.
3618
3619The @samp{%d} conversion matches an optionally signed integer in decimal
3620radix. The syntax that is recognized is the same as that for the
3621@code{strtol} function (@pxref{Parsing of Integers}) with the value
3622@code{10} for the @var{base} argument.
3623
3624The @samp{%i} conversion matches an optionally signed integer in any of
3625the formats that the C language defines for specifying an integer
3626constant. The syntax that is recognized is the same as that for the
3627@code{strtol} function (@pxref{Parsing of Integers}) with the value
3628@code{0} for the @var{base} argument. (You can print integers in this
3629syntax with @code{printf} by using the @samp{#} flag character with the
dee2bea0
JM
3630@samp{%x}, @samp{%o}, @samp{%b}, or @samp{%d} conversion.
3631@xref{Integer Conversions}.)
28f540f4
RM
3632
3633For example, any of the strings @samp{10}, @samp{0xa}, or @samp{012}
3634could be read in as integers under the @samp{%i} conversion. Each of
3635these specifies a number with decimal value @code{10}.
3636
3637The @samp{%o}, @samp{%u}, and @samp{%x} conversions match unsigned
3638integers in octal, decimal, and hexadecimal radices, respectively. The
3639syntax that is recognized is the same as that for the @code{strtoul}
3640function (@pxref{Parsing of Integers}) with the appropriate value
3641(@code{8}, @code{10}, or @code{16}) for the @var{base} argument.
3642
3643The @samp{%X} conversion is identical to the @samp{%x} conversion. They
3644both permit either uppercase or lowercase letters to be used as digits.
3645
4d8d70d3
AR
3646The default type of the corresponding argument for the @code{%d},
3647@code{%i}, and @code{%n} conversions is @code{int *}, and
3648@code{unsigned int *} for the other integer conversions. You can use
3649the following type modifiers to specify other sizes of integer:
28f540f4
RM
3650
3651@table @samp
cc3fa755
UD
3652@item hh
3653Specifies that the argument is a @code{signed char *} or @code{unsigned
3654char *}.
3655
ec751a23 3656This modifier was introduced in @w{ISO C99}.
e852e889 3657
28f540f4
RM
3658@item h
3659Specifies that the argument is a @code{short int *} or @code{unsigned
3660short int *}.
3661
e852e889
UD
3662@item j
3663Specifies that the argument is a @code{intmax_t *} or @code{uintmax_t *}.
3664
ec751a23 3665This modifier was introduced in @w{ISO C99}.
e852e889 3666
28f540f4
RM
3667@item l
3668Specifies that the argument is a @code{long int *} or @code{unsigned
3669long int *}. Two @samp{l} characters is like the @samp{L} modifier, below.
3670
b5e73f56
UD
3671If used with @samp{%c} or @samp{%s} the corresponding parameter is
3672considered as a pointer to a wide character or wide character string
3673respectively. This use of @samp{l} was introduced in @w{Amendment 1} to
3674@w{ISO C90}.
3675
28f540f4
RM
3676@need 100
3677@item ll
3678@itemx L
3679@itemx q
3680Specifies that the argument is a @code{long long int *} or @code{unsigned long long int *}. (The @code{long long} type is an extension supported by the
3681GNU C compiler. For systems that don't provide extra-long integers, this
3682is the same as @code{long int}.)
3683
3684The @samp{q} modifier is another name for the same thing, which comes
3685from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
3686@code{int}.
e852e889
UD
3687
3688@item t
3689Specifies that the argument is a @code{ptrdiff_t *}.
3690
ec751a23 3691This modifier was introduced in @w{ISO C99}.
e852e889
UD
3692
3693@item z
3694Specifies that the argument is a @code{size_t *}.
3695
ec751a23 3696This modifier was introduced in @w{ISO C99}.
28f540f4
RM
3697@end table
3698
0674613e 3699All of the @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%F} and @samp{%G}
28f540f4
RM
3700input conversions are interchangeable. They all match an optionally
3701signed floating point number, in the same syntax as for the
3702@code{strtod} function (@pxref{Parsing of Floats}).
3703
3704For the floating-point input conversions, the default argument type is
3705@code{float *}. (This is different from the corresponding output
3706conversions, where the default type is @code{double}; remember that
3707@code{float} arguments to @code{printf} are converted to @code{double}
3708by the default argument promotions, but @code{float *} arguments are
3709not promoted to @code{double *}.) You can specify other sizes of float
3710using these type modifiers:
3711
3712@table @samp
3713@item l
3714Specifies that the argument is of type @code{double *}.
3715
3716@item L
3717Specifies that the argument is of type @code{long double *}.
3718@end table
3719
2c6fe0bd
UD
3720For all the above number parsing formats there is an additional optional
3721flag @samp{'}. When this flag is given the @code{scanf} function
3722expects the number represented in the input string to be formatted
3723according to the grouping rules of the currently selected locale
3724(@pxref{General Numeric}).
3725
3726If the @code{"C"} or @code{"POSIX"} locale is selected there is no
3727difference. But for a locale which specifies values for the appropriate
3728fields in the locale the input must have the correct form in the input.
3729Otherwise the longest prefix with a correct form is processed.
3730
28f540f4
RM
3731@node String Input Conversions
3732@subsection String Input Conversions
3733
3734This section describes the @code{scanf} input conversions for reading
b5e73f56
UD
3735string and character values: @samp{%s}, @samp{%S}, @samp{%[}, @samp{%c},
3736and @samp{%C}.
28f540f4
RM
3737
3738You have two options for how to receive the input from these
3739conversions:
3740
3741@itemize @bullet
3742@item
b5e73f56
UD
3743Provide a buffer to store it in. This is the default. You should
3744provide an argument of type @code{char *} or @code{wchar_t *} (the
c703cd7a 3745latter if the @samp{l} modifier is present).
28f540f4
RM
3746
3747@strong{Warning:} To make a robust program, you must make sure that the
3748input (plus its terminating null) cannot possibly exceed the size of the
3749buffer you provide. In general, the only way to do this is to specify a
3750maximum field width one less than the buffer size. @strong{If you
3751provide the buffer, always specify a maximum field width to prevent
3752overflow.}
3753
3754@item
3755Ask @code{scanf} to allocate a big enough buffer, by specifying the
3756@samp{a} flag character. This is a GNU extension. You should provide
3757an argument of type @code{char **} for the buffer address to be stored
3758in. @xref{Dynamic String Input}.
3759@end itemize
3760
3761The @samp{%c} conversion is the simplest: it matches a fixed number of
04b9968b 3762characters, always. The maximum field width says how many characters to
28f540f4
RM
3763read; if you don't specify the maximum, the default is 1. This
3764conversion doesn't append a null character to the end of the text it
3765reads. It also does not skip over initial whitespace characters. It
3766reads precisely the next @var{n} characters, and fails if it cannot get
3767that many. Since there is always a maximum field width with @samp{%c}
3768(whether specified, or 1 by default), you can always prevent overflow by
3769making the buffer long enough.
b5e73f56
UD
3770@comment Is character == byte here??? --drepper
3771
3772If the format is @samp{%lc} or @samp{%C} the function stores wide
3773characters which are converted using the conversion determined at the
3774time the stream was opened from the external byte stream. The number of
3775bytes read from the medium is limited by @code{MB_CUR_LEN * @var{n}} but
c703cd7a 3776at most @var{n} wide characters get stored in the output string.
28f540f4
RM
3777
3778The @samp{%s} conversion matches a string of non-whitespace characters.
3779It skips and discards initial whitespace, but stops when it encounters
3780more whitespace after having read something. It stores a null character
3781at the end of the text that it reads.
3782
3783For example, reading the input:
3784
3785@smallexample
3786 hello, world
3787@end smallexample
3788
3789@noindent
3790with the conversion @samp{%10c} produces @code{" hello, wo"}, but
3791reading the same input with the conversion @samp{%10s} produces
3792@code{"hello,"}.
3793
3794@strong{Warning:} If you do not specify a field width for @samp{%s},
3795then the number of characters read is limited only by where the next
3796whitespace character appears. This almost certainly means that invalid
3797input can make your program crash---which is a bug.
3798
b5e73f56
UD
3799The @samp{%ls} and @samp{%S} format are handled just like @samp{%s}
3800except that the external byte sequence is converted using the conversion
3801associated with the stream to wide characters with their own encoding.
3802A width or precision specified with the format do not directly determine
3803how many bytes are read from the stream since they measure wide
3804characters. But an upper limit can be computed by multiplying the value
3805of the width or precision by @code{MB_CUR_MAX}.
3806
28f540f4
RM
3807To read in characters that belong to an arbitrary set of your choice,
3808use the @samp{%[} conversion. You specify the set between the @samp{[}
3809character and a following @samp{]} character, using the same syntax used
9878ad46 3810in regular expressions for explicit sets of characters. As special cases:
28f540f4
RM
3811
3812@itemize @bullet
19c3f208 3813@item
28f540f4
RM
3814A literal @samp{]} character can be specified as the first character
3815of the set.
3816
19c3f208 3817@item
28f540f4
RM
3818An embedded @samp{-} character (that is, one that is not the first or
3819last character of the set) is used to specify a range of characters.
3820
19c3f208 3821@item
28f540f4 3822If a caret character @samp{^} immediately follows the initial @samp{[},
c703cd7a 3823then the set of allowed input characters is everything @emph{except}
28f540f4
RM
3824the characters listed.
3825@end itemize
3826
3827The @samp{%[} conversion does not skip over initial whitespace
3828characters.
3829
9878ad46
OB
3830Note that the @dfn{character class} syntax available in character sets
3831that appear inside regular expressions (such as @samp{[:alpha:]}) is
3832@emph{not} available in the @samp{%[} conversion.
3833
28f540f4
RM
3834Here are some examples of @samp{%[} conversions and what they mean:
3835
3836@table @samp
3837@item %25[1234567890]
3838Matches a string of up to 25 digits.
3839
3840@item %25[][]
3841Matches a string of up to 25 square brackets.
3842
3843@item %25[^ \f\n\r\t\v]
3844Matches a string up to 25 characters long that doesn't contain any of
3845the standard whitespace characters. This is slightly different from
3846@samp{%s}, because if the input begins with a whitespace character,
3847@samp{%[} reports a matching failure while @samp{%s} simply discards the
3848initial whitespace.
3849
19c3f208 3850@item %25[a-z]
28f540f4
RM
3851Matches up to 25 lowercase characters.
3852@end table
3853
b5e73f56
UD
3854As for @samp{%c} and @samp{%s} the @samp{%[} format is also modified to
3855produce wide characters if the @samp{l} modifier is present. All what
3856is said about @samp{%ls} above is true for @samp{%l[}.
3857
28f540f4
RM
3858One more reminder: the @samp{%s} and @samp{%[} conversions are
3859@strong{dangerous} if you don't specify a maximum width or use the
3860@samp{a} flag, because input too long would overflow whatever buffer you
3861have provided for it. No matter how long your buffer is, a user could
3862supply input that is longer. A well-written program reports invalid
3863input with a comprehensible error message, not with a crash.
3864
3865@node Dynamic String Input
3866@subsection Dynamically Allocating String Conversions
3867
3868A GNU extension to formatted input lets you safely read a string with no
3869maximum size. Using this feature, you don't supply a buffer; instead,
3870@code{scanf} allocates a buffer big enough to hold the data and gives
3871you its address. To use this feature, write @samp{a} as a flag
3872character, as in @samp{%as} or @samp{%a[0-9a-z]}.
3873
3874The pointer argument you supply for where to store the input should have
3875type @code{char **}. The @code{scanf} function allocates a buffer and
3876stores its address in the word that the argument points to. You should
3877free the buffer with @code{free} when you no longer need it.
3878
3879Here is an example of using the @samp{a} flag with the @samp{%[@dots{}]}
3880conversion specification to read a ``variable assignment'' of the form
3881@samp{@var{variable} = @var{value}}.
3882
3883@smallexample
3884@{
3885 char *variable, *value;
3886
3887 if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n",
162ba701 3888 &variable, &value))
28f540f4
RM
3889 @{
3890 invalid_input_error ();
3891 return 0;
3892 @}
3893
3894 @dots{}
3895@}
3896@end smallexample
3897
3898@node Other Input Conversions
3899@subsection Other Input Conversions
3900
3901This section describes the miscellaneous input conversions.
3902
3903The @samp{%p} conversion is used to read a pointer value. It recognizes
04b9968b 3904the same syntax used by the @samp{%p} output conversion for
28f540f4
RM
3905@code{printf} (@pxref{Other Output Conversions}); that is, a hexadecimal
3906number just as the @samp{%x} conversion accepts. The corresponding
3907argument should be of type @code{void **}; that is, the address of a
3908place to store a pointer.
3909
3910The resulting pointer value is not guaranteed to be valid if it was not
3911originally written during the same program execution that reads it in.
3912
3913The @samp{%n} conversion produces the number of characters read so far
4d8d70d3
AR
3914by this call. The corresponding argument should be of type @code{int *},
3915unless a type modifier is in effect (@pxref{Numeric Input Conversions}).
28f540f4
RM
3916This conversion works in the same way as the @samp{%n} conversion for
3917@code{printf}; see @ref{Other Output Conversions}, for an example.
3918
3919The @samp{%n} conversion is the only mechanism for determining the
3920success of literal matches or conversions with suppressed assignments.
3921If the @samp{%n} follows the locus of a matching failure, then no value
3922is stored for it since @code{scanf} returns before processing the
3923@samp{%n}. If you store @code{-1} in that argument slot before calling
3924@code{scanf}, the presence of @code{-1} after @code{scanf} indicates an
3925error occurred before the @samp{%n} was reached.
3926
3927Finally, the @samp{%%} conversion matches a literal @samp{%} character
3928in the input stream, without using an argument. This conversion does
3929not permit any flags, field width, or type modifier to be specified.
3930
3931@node Formatted Input Functions
3932@subsection Formatted Input Functions
3933
3934Here are the descriptions of the functions for performing formatted
3935input.
3936Prototypes for these functions are in the header file @file{stdio.h}.
3937@pindex stdio.h
3938
28f540f4 3939@deftypefun int scanf (const char *@var{template}, @dots{})
d08a7e4c 3940@standards{ISO, stdio.h}
171e9210 3941@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
3942The @code{scanf} function reads formatted input from the stream
3943@code{stdin} under the control of the template string @var{template}.
3944The optional arguments are pointers to the places which receive the
3945resulting values.
3946
3947The return value is normally the number of successful assignments. If
04b9968b
UD
3948an end-of-file condition is detected before any matches are performed,
3949including matches against whitespace and literal characters in the
3950template, then @code{EOF} is returned.
28f540f4
RM
3951@end deftypefun
3952
b5e73f56 3953@deftypefun int wscanf (const wchar_t *@var{template}, @dots{})
d08a7e4c 3954@standards{ISO, wchar.h}
171e9210 3955@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
3956The @code{wscanf} function reads formatted input from the stream
3957@code{stdin} under the control of the template string @var{template}.
3958The optional arguments are pointers to the places which receive the
3959resulting values.
3960
3961The return value is normally the number of successful assignments. If
3962an end-of-file condition is detected before any matches are performed,
3963including matches against whitespace and literal characters in the
3964template, then @code{WEOF} is returned.
3965@end deftypefun
3966
28f540f4 3967@deftypefun int fscanf (FILE *@var{stream}, const char *@var{template}, @dots{})
d08a7e4c 3968@standards{ISO, stdio.h}
171e9210 3969@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
3970This function is just like @code{scanf}, except that the input is read
3971from the stream @var{stream} instead of @code{stdin}.
3972@end deftypefun
3973
b5e73f56 3974@deftypefun int fwscanf (FILE *@var{stream}, const wchar_t *@var{template}, @dots{})
d08a7e4c 3975@standards{ISO, wchar.h}
171e9210 3976@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
3977This function is just like @code{wscanf}, except that the input is read
3978from the stream @var{stream} instead of @code{stdin}.
3979@end deftypefun
3980
28f540f4 3981@deftypefun int sscanf (const char *@var{s}, const char *@var{template}, @dots{})
d08a7e4c 3982@standards{ISO, stdio.h}
171e9210 3983@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
3984This is like @code{scanf}, except that the characters are taken from the
3985null-terminated string @var{s} instead of from a stream. Reaching the
3986end of the string is treated as an end-of-file condition.
3987
3988The behavior of this function is undefined if copying takes place
3989between objects that overlap---for example, if @var{s} is also given
b5e73f56
UD
3990as an argument to receive a string read under control of the @samp{%s},
3991@samp{%S}, or @samp{%[} conversion.
3992@end deftypefun
3993
8ded91fb 3994@deftypefun int swscanf (const wchar_t *@var{ws}, const wchar_t *@var{template}, @dots{})
d08a7e4c 3995@standards{ISO, wchar.h}
171e9210 3996@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b5e73f56
UD
3997This is like @code{wscanf}, except that the characters are taken from the
3998null-terminated string @var{ws} instead of from a stream. Reaching the
3999end of the string is treated as an end-of-file condition.
4000
4001The behavior of this function is undefined if copying takes place
4002between objects that overlap---for example, if @var{ws} is also given as
4003an argument to receive a string read under control of the @samp{%s},
4004@samp{%S}, or @samp{%[} conversion.
28f540f4
RM
4005@end deftypefun
4006
4007@node Variable Arguments Input
4008@subsection Variable Arguments Input Functions
4009
4010The functions @code{vscanf} and friends are provided so that you can
4011define your own variadic @code{scanf}-like functions that make use of
4012the same internals as the built-in formatted output functions.
4013These functions are analogous to the @code{vprintf} series of output
4014functions. @xref{Variable Arguments Output}, for important
4015information on how to use them.
4016
b5e73f56
UD
4017@strong{Portability Note:} The functions listed in this section were
4018introduced in @w{ISO C99} and were before available as GNU extensions.
28f540f4 4019
28f540f4 4020@deftypefun int vscanf (const char *@var{template}, va_list @var{ap})
d08a7e4c 4021@standards{ISO, stdio.h}
171e9210 4022@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
04b9968b 4023This function is similar to @code{scanf}, but instead of taking
28f540f4
RM
4024a variable number of arguments directly, it takes an argument list
4025pointer @var{ap} of type @code{va_list} (@pxref{Variadic Functions}).
4026@end deftypefun
4027
b5e73f56 4028@deftypefun int vwscanf (const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 4029@standards{ISO, wchar.h}
171e9210 4030@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
4031This function is similar to @code{wscanf}, but instead of taking
4032a variable number of arguments directly, it takes an argument list
4033pointer @var{ap} of type @code{va_list} (@pxref{Variadic Functions}).
4034@end deftypefun
4035
28f540f4 4036@deftypefun int vfscanf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
d08a7e4c 4037@standards{ISO, stdio.h}
171e9210 4038@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
28f540f4
RM
4039This is the equivalent of @code{fscanf} with the variable argument list
4040specified directly as for @code{vscanf}.
4041@end deftypefun
4042
b5e73f56 4043@deftypefun int vfwscanf (FILE *@var{stream}, const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 4044@standards{ISO, wchar.h}
171e9210 4045@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@asucorrupt{} @ascuheap{}}@acunsafe{@acsmem{} @aculock{} @acucorrupt{}}}
b5e73f56
UD
4046This is the equivalent of @code{fwscanf} with the variable argument list
4047specified directly as for @code{vwscanf}.
4048@end deftypefun
4049
28f540f4 4050@deftypefun int vsscanf (const char *@var{s}, const char *@var{template}, va_list @var{ap})
d08a7e4c 4051@standards{ISO, stdio.h}
171e9210 4052@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4
RM
4053This is the equivalent of @code{sscanf} with the variable argument list
4054specified directly as for @code{vscanf}.
4055@end deftypefun
4056
b5e73f56 4057@deftypefun int vswscanf (const wchar_t *@var{s}, const wchar_t *@var{template}, va_list @var{ap})
d08a7e4c 4058@standards{ISO, wchar.h}
171e9210 4059@safety{@prelim{}@mtsafe{@mtslocale{}}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
b5e73f56
UD
4060This is the equivalent of @code{swscanf} with the variable argument list
4061specified directly as for @code{vwscanf}.
4062@end deftypefun
4063
28f540f4
RM
4064In GNU C, there is a special construct you can use to let the compiler
4065know that a function uses a @code{scanf}-style format string. Then it
4066can check the number and types of arguments in each call to the
4067function, and warn you when they do not match the format string.
88197030 4068For details, see @ref{Function Attributes, , Declaring Attributes of Functions,
1f6676d7 4069gcc, Using GNU CC}.
28f540f4
RM
4070
4071@node EOF and Errors
4072@section End-Of-File and Errors
4073
4074@cindex end of file, on a stream
4075Many of the functions described in this chapter return the value of the
4076macro @code{EOF} to indicate unsuccessful completion of the operation.
4077Since @code{EOF} is used to report both end of file and random errors,
4078it's often better to use the @code{feof} function to check explicitly
4079for end of file and @code{ferror} to check for errors. These functions
4080check indicators that are part of the internal state of the stream
4081object, indicators set if the appropriate condition was detected by a
4082previous I/O operation on that stream.
4083
28f540f4 4084@deftypevr Macro int EOF
d08a7e4c 4085@standards{ISO, stdio.h}
b5e73f56
UD
4086This macro is an integer value that is returned by a number of narrow
4087stream functions to indicate an end-of-file condition, or some other
1f77f049 4088error situation. With @theglibc{}, @code{EOF} is @code{-1}. In
b5e73f56
UD
4089other libraries, its value may be some other negative number.
4090
4091This symbol is declared in @file{stdio.h}.
4092@end deftypevr
4093
b5e73f56 4094@deftypevr Macro int WEOF
d08a7e4c 4095@standards{ISO, wchar.h}
b5e73f56
UD
4096This macro is an integer value that is returned by a number of wide
4097stream functions to indicate an end-of-file condition, or some other
1f77f049 4098error situation. With @theglibc{}, @code{WEOF} is @code{-1}. In
b5e73f56
UD
4099other libraries, its value may be some other negative number.
4100
4101This symbol is declared in @file{wchar.h}.
28f540f4
RM
4102@end deftypevr
4103
28f540f4 4104@deftypefun int feof (FILE *@var{stream})
d08a7e4c 4105@standards{ISO, stdio.h}
171e9210 4106@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
28f540f4
RM
4107The @code{feof} function returns nonzero if and only if the end-of-file
4108indicator for the stream @var{stream} is set.
b5e73f56
UD
4109
4110This symbol is declared in @file{stdio.h}.
28f540f4
RM
4111@end deftypefun
4112
7b4161bb 4113@deftypefun int feof_unlocked (FILE *@var{stream})
d08a7e4c 4114@standards{GNU, stdio.h}
171e9210
AO
4115@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
4116@c There isn't much of a thread unsafety risk in reading a flag word and
4117@c testing a bit in it.
7b4161bb 4118The @code{feof_unlocked} function is equivalent to the @code{feof}
1dc843f7 4119function except that it does not implicitly lock the stream.
7b4161bb
UD
4120
4121This function is a GNU extension.
b5e73f56
UD
4122
4123This symbol is declared in @file{stdio.h}.
7b4161bb
UD
4124@end deftypefun
4125
28f540f4 4126@deftypefun int ferror (FILE *@var{stream})
d08a7e4c 4127@standards{ISO, stdio.h}
171e9210 4128@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
28f540f4
RM
4129The @code{ferror} function returns nonzero if and only if the error
4130indicator for the stream @var{stream} is set, indicating that an error
4131has occurred on a previous operation on the stream.
b5e73f56
UD
4132
4133This symbol is declared in @file{stdio.h}.
28f540f4
RM
4134@end deftypefun
4135
7b4161bb 4136@deftypefun int ferror_unlocked (FILE *@var{stream})
d08a7e4c 4137@standards{GNU, stdio.h}
171e9210 4138@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
7b4161bb 4139The @code{ferror_unlocked} function is equivalent to the @code{ferror}
1dc843f7 4140function except that it does not implicitly lock the stream.
7b4161bb
UD
4141
4142This function is a GNU extension.
b5e73f56
UD
4143
4144This symbol is declared in @file{stdio.h}.
7b4161bb
UD
4145@end deftypefun
4146
28f540f4
RM
4147In addition to setting the error indicator associated with the stream,
4148the functions that operate on streams also set @code{errno} in the same
4149way as the corresponding low-level functions that operate on file
4150descriptors. For example, all of the functions that perform output to a
4151stream---such as @code{fputc}, @code{printf}, and @code{fflush}---are
4152implemented in terms of @code{write}, and all of the @code{errno} error
4153conditions defined for @code{write} are meaningful for these functions.
4154For more information about the descriptor-level I/O functions, see
4155@ref{Low-Level I/O}.
4156
460e040a
UD
4157@node Error Recovery
4158@section Recovering from errors
4159
7ba73c63 4160You may explicitly clear the error and EOF flags with the @code{clearerr}
460e040a
UD
4161function.
4162
460e040a 4163@deftypefun void clearerr (FILE *@var{stream})
d08a7e4c 4164@standards{ISO, stdio.h}
171e9210 4165@safety{@prelim{}@mtsafe{}@assafe{}@acunsafe{@aculock{}}}
460e040a
UD
4166This function clears the end-of-file and error indicators for the
4167stream @var{stream}.
4168
4169The file positioning functions (@pxref{File Positioning}) also clear the
4170end-of-file indicator for the stream.
4171@end deftypefun
4172
7b4161bb 4173@deftypefun void clearerr_unlocked (FILE *@var{stream})
d08a7e4c 4174@standards{GNU, stdio.h}
171e9210 4175@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@assafe{}@acsafe{}}
7b4161bb 4176The @code{clearerr_unlocked} function is equivalent to the @code{clearerr}
1dc843f7 4177function except that it does not implicitly lock the stream.
7b4161bb
UD
4178
4179This function is a GNU extension.
4180@end deftypefun
4181
460e040a
UD
4182Note that it is @emph{not} correct to just clear the error flag and retry
4183a failed stream operation. After a failed write, any number of
4184characters since the last buffer flush may have been committed to the
4185file, while some buffered data may have been discarded. Merely retrying
4186can thus cause lost or repeated data.
4187
4188A failed read may leave the file pointer in an inappropriate position for
4189a second try. In both cases, you should seek to a known position before
4190retrying.
4191
4192Most errors that can happen are not recoverable --- a second try will
4193always fail again in the same way. So usually it is best to give up and
4194report the error to the user, rather than install complicated recovery
4195logic.
4196
7ba73c63 4197One important exception is @code{EINTR} (@pxref{Interrupted Primitives}).
460e040a
UD
4198Many stream I/O implementations will treat it as an ordinary error, which
4199can be quite inconvenient. You can avoid this hassle by installing all
4200signals with the @code{SA_RESTART} flag.
4201
4202For similar reasons, setting nonblocking I/O on a stream's file
4203descriptor is not usually advisable.
4204
28f540f4
RM
4205@node Binary Streams
4206@section Text and Binary Streams
4207
a7a93d50 4208@gnusystems{} and other POSIX-compatible operating systems organize all
28f540f4
RM
4209files as uniform sequences of characters. However, some other systems
4210make a distinction between files containing text and files containing
f65fd747 4211binary data, and the input and output facilities of @w{ISO C} provide for
28f540f4
RM
4212this distinction. This section tells you how to write programs portable
4213to such systems.
4214
4215@cindex text stream
4216@cindex binary stream
4217When you open a stream, you can specify either a @dfn{text stream} or a
4218@dfn{binary stream}. You indicate that you want a binary stream by
4219specifying the @samp{b} modifier in the @var{opentype} argument to
4220@code{fopen}; see @ref{Opening Streams}. Without this
4221option, @code{fopen} opens the file as a text stream.
4222
4223Text and binary streams differ in several ways:
4224
4225@itemize @bullet
4226@item
4227The data read from a text stream is divided into @dfn{lines} which are
4228terminated by newline (@code{'\n'}) characters, while a binary stream is
4229simply a long series of characters. A text stream might on some systems
4230fail to handle lines more than 254 characters long (including the
4231terminating newline character).
4232@cindex lines (in a text file)
4233
4234@item
4235On some systems, text files can contain only printing characters,
4236horizontal tab characters, and newlines, and so text streams may not
4237support other characters. However, binary streams can handle any
4238character value.
4239
4240@item
4241Space characters that are written immediately preceding a newline
4242character in a text stream may disappear when the file is read in again.
4243
4244@item
4245More generally, there need not be a one-to-one mapping between
4246characters that are read from or written to a text stream, and the
4247characters in the actual file.
4248@end itemize
4249
4250Since a binary stream is always more capable and more predictable than a
4251text stream, you might wonder what purpose text streams serve. Why not
4252simply always use binary streams? The answer is that on these operating
4253systems, text and binary streams use different file formats, and the
4254only way to read or write ``an ordinary file of text'' that can work
4255with other text-oriented programs is through a text stream.
4256
1f77f049 4257In @theglibc{}, and on all POSIX systems, there is no difference
28f540f4
RM
4258between text streams and binary streams. When you open a stream, you
4259get the same kind of stream regardless of whether you ask for binary.
4260This stream can handle any file content, and has none of the
4261restrictions that text streams sometimes have.
4262
4263@node File Positioning
4264@section File Positioning
4265@cindex file positioning on a stream
4266@cindex positioning a stream
4267@cindex seeking on a stream
4268
4269The @dfn{file position} of a stream describes where in the file the
4270stream is currently reading or writing. I/O on the stream advances the
a7a93d50 4271file position through the file. On @gnusystems{}, the file position is
28f540f4
RM
4272represented as an integer, which counts the number of bytes from the
4273beginning of the file. @xref{File Position}.
4274
4275During I/O to an ordinary disk file, you can change the file position
4276whenever you wish, so as to read or write any portion of the file. Some
4277other kinds of files may also permit this. Files which support changing
4278the file position are sometimes referred to as @dfn{random-access}
4279files.
4280
4281You can use the functions in this section to examine or modify the file
4282position indicator associated with a stream. The symbols listed below
4283are declared in the header file @file{stdio.h}.
4284@pindex stdio.h
4285
28f540f4 4286@deftypefun {long int} ftell (FILE *@var{stream})
d08a7e4c 4287@standards{ISO, stdio.h}
171e9210 4288@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4289This function returns the current file position of the stream
4290@var{stream}.
4291
4292This function can fail if the stream doesn't support file positioning,
4293or if the file position can't be represented in a @code{long int}, and
4294possibly for other reasons as well. If a failure occurs, a value of
4295@code{-1} is returned.
4296@end deftypefun
4297
a5a0310d 4298@deftypefun off_t ftello (FILE *@var{stream})
d08a7e4c 4299@standards{Unix98, stdio.h}
171e9210 4300@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
04b9968b
UD
4301The @code{ftello} function is similar to @code{ftell}, except that it
4302returns a value of type @code{off_t}. Systems which support this type
4303use it to describe all file positions, unlike the POSIX specification
4304which uses a long int. The two are not necessarily the same size.
4305Therefore, using ftell can lead to problems if the implementation is
4306written on top of a POSIX compliant low-level I/O implementation, and using
4307@code{ftello} is preferable whenever it is available.
4308
4309If this function fails it returns @code{(off_t) -1}. This can happen due
a5a0310d
UD
4310to missing support for file positioning or internal errors. Otherwise
4311the return value is the current file position.
4312
4313The function is an extension defined in the Unix Single Specification
4314version 2.
a3a4a74e
UD
4315
4316When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 431732 bit system this function is in fact @code{ftello64}. I.e., the
a3a4a74e
UD
4318LFS interface transparently replaces the old interface.
4319@end deftypefun
4320
a3a4a74e 4321@deftypefun off64_t ftello64 (FILE *@var{stream})
d08a7e4c 4322@standards{Unix98, stdio.h}
171e9210 4323@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
a3a4a74e
UD
4324This function is similar to @code{ftello} with the only difference that
4325the return value is of type @code{off64_t}. This also requires that the
4326stream @var{stream} was opened using either @code{fopen64},
4327@code{freopen64}, or @code{tmpfile64} since otherwise the underlying
9ceeb279 4328file operations to position the file pointer beyond the @twoexp{31}
a3a4a74e
UD
4329bytes limit might fail.
4330
4331If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
4332bits machine this function is available under the name @code{ftello}
4333and so transparently replaces the old interface.
a5a0310d
UD
4334@end deftypefun
4335
28f540f4 4336@deftypefun int fseek (FILE *@var{stream}, long int @var{offset}, int @var{whence})
d08a7e4c 4337@standards{ISO, stdio.h}
171e9210 4338@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4339The @code{fseek} function is used to change the file position of the
4340stream @var{stream}. The value of @var{whence} must be one of the
4341constants @code{SEEK_SET}, @code{SEEK_CUR}, or @code{SEEK_END}, to
4342indicate whether the @var{offset} is relative to the beginning of the
4343file, the current file position, or the end of the file, respectively.
4344
4345This function returns a value of zero if the operation was successful,
4346and a nonzero value to indicate failure. A successful call also clears
4347the end-of-file indicator of @var{stream} and discards any characters
4348that were ``pushed back'' by the use of @code{ungetc}.
4349
4350@code{fseek} either flushes any buffered output before setting the file
4351position or else remembers it so it will be written later in its proper
4352place in the file.
4353@end deftypefun
4354
a5a0310d 4355@deftypefun int fseeko (FILE *@var{stream}, off_t @var{offset}, int @var{whence})
d08a7e4c 4356@standards{Unix98, stdio.h}
171e9210 4357@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
a5a0310d
UD
4358This function is similar to @code{fseek} but it corrects a problem with
4359@code{fseek} in a system with POSIX types. Using a value of type
4360@code{long int} for the offset is not compatible with POSIX.
4361@code{fseeko} uses the correct type @code{off_t} for the @var{offset}
4362parameter.
4363
f2ea0f5b 4364For this reason it is a good idea to prefer @code{ftello} whenever it is
a5a0310d
UD
4365available since its functionality is (if different at all) closer the
4366underlying definition.
4367
c703cd7a 4368The functionality and return value are the same as for @code{fseek}.
a5a0310d
UD
4369
4370The function is an extension defined in the Unix Single Specification
4371version 2.
a3a4a74e
UD
4372
4373When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 437432 bit system this function is in fact @code{fseeko64}. I.e., the
a3a4a74e
UD
4375LFS interface transparently replaces the old interface.
4376@end deftypefun
4377
a3a4a74e 4378@deftypefun int fseeko64 (FILE *@var{stream}, off64_t @var{offset}, int @var{whence})
d08a7e4c 4379@standards{Unix98, stdio.h}
171e9210 4380@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
a3a4a74e
UD
4381This function is similar to @code{fseeko} with the only difference that
4382the @var{offset} parameter is of type @code{off64_t}. This also
4383requires that the stream @var{stream} was opened using either
4384@code{fopen64}, @code{freopen64}, or @code{tmpfile64} since otherwise
4385the underlying file operations to position the file pointer beyond the
9ceeb279 4386@twoexp{31} bytes limit might fail.
a3a4a74e
UD
4387
4388If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
4389bits machine this function is available under the name @code{fseeko}
4390and so transparently replaces the old interface.
a5a0310d
UD
4391@end deftypefun
4392
4393@strong{Portability Note:} In non-POSIX systems, @code{ftell},
4394@code{ftello}, @code{fseek} and @code{fseeko} might work reliably only
4395on binary streams. @xref{Binary Streams}.
28f540f4
RM
4396
4397The following symbolic constants are defined for use as the @var{whence}
4398argument to @code{fseek}. They are also used with the @code{lseek}
4399function (@pxref{I/O Primitives}) and to specify offsets for file locks
4400(@pxref{Control Operations}).
4401
28f540f4 4402@deftypevr Macro int SEEK_SET
d08a7e4c 4403@standards{ISO, stdio.h}
28f540f4 4404This is an integer constant which, when used as the @var{whence}
c703cd7a 4405argument to the @code{fseek} or @code{fseeko} functions, specifies that
a5a0310d 4406the offset provided is relative to the beginning of the file.
28f540f4
RM
4407@end deftypevr
4408
28f540f4 4409@deftypevr Macro int SEEK_CUR
d08a7e4c 4410@standards{ISO, stdio.h}
28f540f4 4411This is an integer constant which, when used as the @var{whence}
c703cd7a 4412argument to the @code{fseek} or @code{fseeko} functions, specifies that
a5a0310d 4413the offset provided is relative to the current file position.
28f540f4
RM
4414@end deftypevr
4415
28f540f4 4416@deftypevr Macro int SEEK_END
d08a7e4c 4417@standards{ISO, stdio.h}
28f540f4 4418This is an integer constant which, when used as the @var{whence}
c703cd7a 4419argument to the @code{fseek} or @code{fseeko} functions, specifies that
a5a0310d 4420the offset provided is relative to the end of the file.
28f540f4
RM
4421@end deftypevr
4422
28f540f4 4423@deftypefun void rewind (FILE *@var{stream})
d08a7e4c 4424@standards{ISO, stdio.h}
171e9210 4425@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4 4426The @code{rewind} function positions the stream @var{stream} at the
f2ea0f5b 4427beginning of the file. It is equivalent to calling @code{fseek} or
a5a0310d
UD
4428@code{fseeko} on the @var{stream} with an @var{offset} argument of
4429@code{0L} and a @var{whence} argument of @code{SEEK_SET}, except that
4430the return value is discarded and the error indicator for the stream is
4431reset.
28f540f4
RM
4432@end deftypefun
4433
4434These three aliases for the @samp{SEEK_@dots{}} constants exist for the
4435sake of compatibility with older BSD systems. They are defined in two
4436different header files: @file{fcntl.h} and @file{sys/file.h}.
4437
2fe82ca6 4438@vtable @code
28f540f4 4439@item L_SET
d08a7e4c 4440@standards{BSD, sys/file.h}
28f540f4
RM
4441An alias for @code{SEEK_SET}.
4442
28f540f4 4443@item L_INCR
d08a7e4c 4444@standards{BSD, sys/file.h}
28f540f4
RM
4445An alias for @code{SEEK_CUR}.
4446
28f540f4 4447@item L_XTND
d08a7e4c 4448@standards{BSD, sys/file.h}
28f540f4 4449An alias for @code{SEEK_END}.
2fe82ca6 4450@end vtable
28f540f4
RM
4451
4452@node Portable Positioning
4453@section Portable File-Position Functions
4454
a7a93d50 4455On @gnusystems{}, the file position is truly a character count. You
a5a0310d
UD
4456can specify any character count value as an argument to @code{fseek} or
4457@code{fseeko} and get reliable results for any random access file.
4458However, some @w{ISO C} systems do not represent file positions in this
4459way.
28f540f4
RM
4460
4461On some systems where text streams truly differ from binary streams, it
4462is impossible to represent the file position of a text stream as a count
4463of characters from the beginning of the file. For example, the file
4464position on some systems must encode both a record offset within the
4465file, and a character offset within the record.
4466
4467As a consequence, if you want your programs to be portable to these
4468systems, you must observe certain rules:
4469
4470@itemize @bullet
4471@item
4472The value returned from @code{ftell} on a text stream has no predictable
4473relationship to the number of characters you have read so far. The only
4474thing you can rely on is that you can use it subsequently as the
a5a0310d
UD
4475@var{offset} argument to @code{fseek} or @code{fseeko} to move back to
4476the same file position.
28f540f4 4477
19c3f208 4478@item
a5a0310d 4479In a call to @code{fseek} or @code{fseeko} on a text stream, either the
04b9968b 4480@var{offset} must be zero, or @var{whence} must be @code{SEEK_SET} and
ded5b9b7 4481the @var{offset} must be the result of an earlier call to @code{ftell}
04b9968b 4482on the same stream.
28f540f4
RM
4483
4484@item
4485The value of the file position indicator of a text stream is undefined
4486while there are characters that have been pushed back with @code{ungetc}
4487that haven't been read or discarded. @xref{Unreading}.
4488@end itemize
4489
4490But even if you observe these rules, you may still have trouble for long
4491files, because @code{ftell} and @code{fseek} use a @code{long int} value
4492to represent the file position. This type may not have room to encode
a5a0310d
UD
4493all the file positions in a large file. Using the @code{ftello} and
4494@code{fseeko} functions might help here since the @code{off_t} type is
4495expected to be able to hold all file position values but this still does
4496not help to handle additional information which must be associated with
4497a file position.
28f540f4
RM
4498
4499So if you do want to support systems with peculiar encodings for the
4500file positions, it is better to use the functions @code{fgetpos} and
4501@code{fsetpos} instead. These functions represent the file position
4502using the data type @code{fpos_t}, whose internal representation varies
4503from system to system.
4504
4505These symbols are declared in the header file @file{stdio.h}.
4506@pindex stdio.h
4507
28f540f4 4508@deftp {Data Type} fpos_t
d08a7e4c 4509@standards{ISO, stdio.h}
28f540f4
RM
4510This is the type of an object that can encode information about the
4511file position of a stream, for use by the functions @code{fgetpos} and
4512@code{fsetpos}.
4513
a7a93d50 4514In @theglibc{}, @code{fpos_t} is an opaque data structure that
5988b69d
AJ
4515contains internal data to represent file offset and conversion state
4516information. In other systems, it might have a different internal
28f540f4 4517representation.
a3a4a74e 4518
0be8752b 4519When compiling with @code{_FILE_OFFSET_BITS == 64} on a 32 bit machine
5988b69d
AJ
4520this type is in fact equivalent to @code{fpos64_t} since the LFS
4521interface transparently replaces the old interface.
a3a4a74e
UD
4522@end deftp
4523
a3a4a74e 4524@deftp {Data Type} fpos64_t
d08a7e4c 4525@standards{Unix98, stdio.h}
a3a4a74e
UD
4526This is the type of an object that can encode information about the
4527file position of a stream, for use by the functions @code{fgetpos64} and
4528@code{fsetpos64}.
4529
a7a93d50 4530In @theglibc{}, @code{fpos64_t} is an opaque data structure that
5988b69d
AJ
4531contains internal data to represent file offset and conversion state
4532information. In other systems, it might have a different internal
a3a4a74e 4533representation.
28f540f4
RM
4534@end deftp
4535
28f540f4 4536@deftypefun int fgetpos (FILE *@var{stream}, fpos_t *@var{position})
d08a7e4c 4537@standards{ISO, stdio.h}
171e9210 4538@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4539This function stores the value of the file position indicator for the
4540stream @var{stream} in the @code{fpos_t} object pointed to by
4541@var{position}. If successful, @code{fgetpos} returns zero; otherwise
4542it returns a nonzero value and stores an implementation-defined positive
4543value in @code{errno}.
a3a4a74e
UD
4544
4545When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 454632 bit system the function is in fact @code{fgetpos64}. I.e., the LFS
5988b69d 4547interface transparently replaces the old interface.
a3a4a74e
UD
4548@end deftypefun
4549
a3a4a74e 4550@deftypefun int fgetpos64 (FILE *@var{stream}, fpos64_t *@var{position})
d08a7e4c 4551@standards{Unix98, stdio.h}
171e9210 4552@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
a3a4a74e
UD
4553This function is similar to @code{fgetpos} but the file position is
4554returned in a variable of type @code{fpos64_t} to which @var{position}
4555points.
4556
4557If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
4558bits machine this function is available under the name @code{fgetpos}
4559and so transparently replaces the old interface.
28f540f4
RM
4560@end deftypefun
4561
a3a4a74e 4562@deftypefun int fsetpos (FILE *@var{stream}, const fpos_t *@var{position})
d08a7e4c 4563@standards{ISO, stdio.h}
171e9210 4564@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4565This function sets the file position indicator for the stream @var{stream}
4566to the position @var{position}, which must have been set by a previous
4567call to @code{fgetpos} on the same stream. If successful, @code{fsetpos}
4568clears the end-of-file indicator on the stream, discards any characters
4569that were ``pushed back'' by the use of @code{ungetc}, and returns a value
4570of zero. Otherwise, @code{fsetpos} returns a nonzero value and stores
4571an implementation-defined positive value in @code{errno}.
a3a4a74e
UD
4572
4573When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
0be8752b 457432 bit system the function is in fact @code{fsetpos64}. I.e., the LFS
5988b69d 4575interface transparently replaces the old interface.
a3a4a74e
UD
4576@end deftypefun
4577
a3a4a74e 4578@deftypefun int fsetpos64 (FILE *@var{stream}, const fpos64_t *@var{position})
d08a7e4c 4579@standards{Unix98, stdio.h}
171e9210 4580@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
a3a4a74e
UD
4581This function is similar to @code{fsetpos} but the file position used
4582for positioning is provided in a variable of type @code{fpos64_t} to
4583which @var{position} points.
4584
4585If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
4586bits machine this function is available under the name @code{fsetpos}
4587and so transparently replaces the old interface.
28f540f4
RM
4588@end deftypefun
4589
4590@node Stream Buffering
4591@section Stream Buffering
4592
4593@cindex buffering of streams
4594Characters that are written to a stream are normally accumulated and
4595transmitted asynchronously to the file in a block, instead of appearing
4596as soon as they are output by the application program. Similarly,
4597streams often retrieve input from the host environment in blocks rather
4598than on a character-by-character basis. This is called @dfn{buffering}.
4599
4600If you are writing programs that do interactive input and output using
4601streams, you need to understand how buffering works when you design the
4602user interface to your program. Otherwise, you might find that output
4603(such as progress or prompt messages) doesn't appear when you intended
04b9968b 4604it to, or displays some other unexpected behavior.
28f540f4
RM
4605
4606This section deals only with controlling when characters are transmitted
4607between the stream and the file or device, and @emph{not} with how
4608things like echoing, flow control, and the like are handled on specific
4609classes of devices. For information on common control operations on
4610terminal devices, see @ref{Low-Level Terminal Interface}.
4611
4612You can bypass the stream buffering facilities altogether by using the
4613low-level input and output functions that operate on file descriptors
4614instead. @xref{Low-Level I/O}.
4615
4616@menu
4617* Buffering Concepts:: Terminology is defined here.
4618* Flushing Buffers:: How to ensure that output buffers are flushed.
4619* Controlling Buffering:: How to specify what kind of buffering to use.
4620@end menu
4621
4622@node Buffering Concepts
4623@subsection Buffering Concepts
4624
4625There are three different kinds of buffering strategies:
4626
4627@itemize @bullet
4628@item
4629Characters written to or read from an @dfn{unbuffered} stream are
4630transmitted individually to or from the file as soon as possible.
4631@cindex unbuffered stream
4632
4633@item
4634Characters written to a @dfn{line buffered} stream are transmitted to
4635the file in blocks when a newline character is encountered.
4636@cindex line buffered stream
4637
4638@item
4639Characters written to or read from a @dfn{fully buffered} stream are
4640transmitted to or from the file in blocks of arbitrary size.
4641@cindex fully buffered stream
4642@end itemize
4643
4644Newly opened streams are normally fully buffered, with one exception: a
4645stream connected to an interactive device such as a terminal is
4646initially line buffered. @xref{Controlling Buffering}, for information
4647on how to select a different kind of buffering. Usually the automatic
4648selection gives you the most convenient kind of buffering for the file
4649or device you open.
4650
4651The use of line buffering for interactive devices implies that output
4652messages ending in a newline will appear immediately---which is usually
4653what you want. Output that doesn't end in a newline might or might not
4654show up immediately, so if you want them to appear immediately, you
4655should flush buffered output explicitly with @code{fflush}, as described
4656in @ref{Flushing Buffers}.
4657
4658@node Flushing Buffers
4659@subsection Flushing Buffers
4660
4661@cindex flushing a stream
4662@dfn{Flushing} output on a buffered stream means transmitting all
4663accumulated characters to the file. There are many circumstances when
4664buffered output on a stream is flushed automatically:
4665
4666@itemize @bullet
4667@item
4668When you try to do output and the output buffer is full.
4669
4670@item
4671When the stream is closed. @xref{Closing Streams}.
4672
19c3f208 4673@item
28f540f4
RM
4674When the program terminates by calling @code{exit}.
4675@xref{Normal Termination}.
4676
4677@item
4678When a newline is written, if the stream is line buffered.
4679
4680@item
4681Whenever an input operation on @emph{any} stream actually reads data
4682from its file.
4683@end itemize
4684
4685If you want to flush the buffered output at another time, call
4686@code{fflush}, which is declared in the header file @file{stdio.h}.
4687@pindex stdio.h
4688
28f540f4 4689@deftypefun int fflush (FILE *@var{stream})
d08a7e4c 4690@standards{ISO, stdio.h}
171e9210 4691@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4692This function causes any buffered output on @var{stream} to be delivered
4693to the file. If @var{stream} is a null pointer, then
4694@code{fflush} causes buffered output on @emph{all} open output streams
4695to be flushed.
4696
4697This function returns @code{EOF} if a write error occurs, or zero
4698otherwise.
4699@end deftypefun
4700
7b4161bb 4701@deftypefun int fflush_unlocked (FILE *@var{stream})
d08a7e4c 4702@standards{POSIX, stdio.h}
171e9210 4703@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb 4704The @code{fflush_unlocked} function is equivalent to the @code{fflush}
1dc843f7 4705function except that it does not implicitly lock the stream.
7b4161bb
UD
4706@end deftypefun
4707
4708The @code{fflush} function can be used to flush all streams currently
4709opened. While this is useful in some situations it does often more than
4710necessary since it might be done in situations when terminal input is
4711required and the program wants to be sure that all output is visible on
4712the terminal. But this means that only line buffered streams have to be
4713flushed. Solaris introduced a function especially for this. It was
1f77f049 4714always available in @theglibc{} in some form but never officially
7b4161bb
UD
4715exported.
4716
7b4161bb 4717@deftypefun void _flushlbf (void)
d08a7e4c 4718@standards{GNU, stdio_ext.h}
171e9210 4719@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
7b4161bb
UD
4720The @code{_flushlbf} function flushes all line buffered streams
4721currently opened.
4722
4723This function is declared in the @file{stdio_ext.h} header.
4724@end deftypefun
4725
28f540f4
RM
4726@strong{Compatibility Note:} Some brain-damaged operating systems have
4727been known to be so thoroughly fixated on line-oriented input and output
4728that flushing a line buffered stream causes a newline to be written!
4729Fortunately, this ``feature'' seems to be becoming less common. You do
a7a93d50 4730not need to worry about this with @theglibc{}.
28f540f4 4731
7b4161bb
UD
4732In some situations it might be useful to not flush the output pending
4733for a stream but instead simply forget it. If transmission is costly
4734and the output is not needed anymore this is valid reasoning. In this
4735situation a non-standard function introduced in Solaris and available in
1f77f049 4736@theglibc{} can be used.
7b4161bb 4737
7b4161bb 4738@deftypefun void __fpurge (FILE *@var{stream})
d08a7e4c 4739@standards{GNU, stdio_ext.h}
171e9210 4740@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acunsafe{@acucorrupt{}}}
7b4161bb
UD
4741The @code{__fpurge} function causes the buffer of the stream
4742@var{stream} to be emptied. If the stream is currently in read mode all
4743input in the buffer is lost. If the stream is in output mode the
4744buffered output is not written to the device (or whatever other
c703cd7a 4745underlying storage) and the buffer is cleared.
7b4161bb
UD
4746
4747This function is declared in @file{stdio_ext.h}.
4748@end deftypefun
28f540f4
RM
4749
4750@node Controlling Buffering
4751@subsection Controlling Which Kind of Buffering
4752
4753After opening a stream (but before any other operations have been
4754performed on it), you can explicitly specify what kind of buffering you
4755want it to have using the @code{setvbuf} function.
4756@cindex buffering, controlling
4757
4758The facilities listed in this section are declared in the header
4759file @file{stdio.h}.
4760@pindex stdio.h
4761
28f540f4 4762@deftypefun int setvbuf (FILE *@var{stream}, char *@var{buf}, int @var{mode}, size_t @var{size})
d08a7e4c 4763@standards{ISO, stdio.h}
171e9210 4764@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4765This function is used to specify that the stream @var{stream} should
4766have the buffering mode @var{mode}, which can be either @code{_IOFBF}
4767(for full buffering), @code{_IOLBF} (for line buffering), or
4768@code{_IONBF} (for unbuffered input/output).
4769
4770If you specify a null pointer as the @var{buf} argument, then @code{setvbuf}
4771allocates a buffer itself using @code{malloc}. This buffer will be freed
4772when you close the stream.
4773
4774Otherwise, @var{buf} should be a character array that can hold at least
4775@var{size} characters. You should not free the space for this array as
4776long as the stream remains open and this array remains its buffer. You
4777should usually either allocate it statically, or @code{malloc}
4778(@pxref{Unconstrained Allocation}) the buffer. Using an automatic array
4779is not a good idea unless you close the file before exiting the block
4780that declares the array.
4781
4782While the array remains a stream buffer, the stream I/O functions will
4783use the buffer for their internal purposes. You shouldn't try to access
4784the values in the array directly while the stream is using it for
4785buffering.
4786
4787The @code{setvbuf} function returns zero on success, or a nonzero value
4788if the value of @var{mode} is not valid or if the request could not
4789be honored.
4790@end deftypefun
4791
28f540f4 4792@deftypevr Macro int _IOFBF
d08a7e4c 4793@standards{ISO, stdio.h}
28f540f4
RM
4794The value of this macro is an integer constant expression that can be
4795used as the @var{mode} argument to the @code{setvbuf} function to
4796specify that the stream should be fully buffered.
4797@end deftypevr
4798
28f540f4 4799@deftypevr Macro int _IOLBF
d08a7e4c 4800@standards{ISO, stdio.h}
28f540f4
RM
4801The value of this macro is an integer constant expression that can be
4802used as the @var{mode} argument to the @code{setvbuf} function to
4803specify that the stream should be line buffered.
4804@end deftypevr
4805
28f540f4 4806@deftypevr Macro int _IONBF
d08a7e4c 4807@standards{ISO, stdio.h}
28f540f4
RM
4808The value of this macro is an integer constant expression that can be
4809used as the @var{mode} argument to the @code{setvbuf} function to
4810specify that the stream should be unbuffered.
4811@end deftypevr
4812
28f540f4 4813@deftypevr Macro int BUFSIZ
d08a7e4c 4814@standards{ISO, stdio.h}
28f540f4
RM
4815The value of this macro is an integer constant expression that is good
4816to use for the @var{size} argument to @code{setvbuf}. This value is
4817guaranteed to be at least @code{256}.
4818
4819The value of @code{BUFSIZ} is chosen on each system so as to make stream
19c3f208 4820I/O efficient. So it is a good idea to use @code{BUFSIZ} as the size
28f540f4
RM
4821for the buffer when you call @code{setvbuf}.
4822
4823Actually, you can get an even better value to use for the buffer size
4824by means of the @code{fstat} system call: it is found in the
4825@code{st_blksize} field of the file attributes. @xref{Attribute Meanings}.
4826
4827Sometimes people also use @code{BUFSIZ} as the allocation size of
4828buffers used for related purposes, such as strings used to receive a
4829line of input with @code{fgets} (@pxref{Character Input}). There is no
4830particular reason to use @code{BUFSIZ} for this instead of any other
4831integer, except that it might lead to doing I/O in chunks of an
4832efficient size.
4833@end deftypevr
4834
28f540f4 4835@deftypefun void setbuf (FILE *@var{stream}, char *@var{buf})
d08a7e4c 4836@standards{ISO, stdio.h}
171e9210 4837@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4838If @var{buf} is a null pointer, the effect of this function is
4839equivalent to calling @code{setvbuf} with a @var{mode} argument of
4840@code{_IONBF}. Otherwise, it is equivalent to calling @code{setvbuf}
4841with @var{buf}, and a @var{mode} of @code{_IOFBF} and a @var{size}
4842argument of @code{BUFSIZ}.
4843
4844The @code{setbuf} function is provided for compatibility with old code;
4845use @code{setvbuf} in all new programs.
4846@end deftypefun
4847
28f540f4 4848@deftypefun void setbuffer (FILE *@var{stream}, char *@var{buf}, size_t @var{size})
d08a7e4c 4849@standards{BSD, stdio.h}
171e9210 4850@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4851If @var{buf} is a null pointer, this function makes @var{stream} unbuffered.
4852Otherwise, it makes @var{stream} fully buffered using @var{buf} as the
4853buffer. The @var{size} argument specifies the length of @var{buf}.
4854
4855This function is provided for compatibility with old BSD code. Use
4856@code{setvbuf} instead.
4857@end deftypefun
4858
28f540f4 4859@deftypefun void setlinebuf (FILE *@var{stream})
d08a7e4c 4860@standards{BSD, stdio.h}
171e9210 4861@safety{@prelim{}@mtsafe{}@asunsafe{@asucorrupt{}}@acunsafe{@aculock{} @acucorrupt{}}}
28f540f4
RM
4862This function makes @var{stream} be line buffered, and allocates the
4863buffer for you.
4864
4865This function is provided for compatibility with old BSD code. Use
4866@code{setvbuf} instead.
4867@end deftypefun
4868
7b4161bb 4869It is possible to query whether a given stream is line buffered or not
1f77f049
JM
4870using a non-standard function introduced in Solaris and available in
4871@theglibc{}.
7b4161bb 4872
7b4161bb 4873@deftypefun int __flbf (FILE *@var{stream})
d08a7e4c 4874@standards{GNU, stdio_ext.h}
171e9210 4875@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
7b4161bb
UD
4876The @code{__flbf} function will return a nonzero value in case the
4877stream @var{stream} is line buffered. Otherwise the return value is
4878zero.
4879
4880This function is declared in the @file{stdio_ext.h} header.
4881@end deftypefun
4882
4883Two more extensions allow to determine the size of the buffer and how
4884much of it is used. These functions were also introduced in Solaris.
4885
7b4161bb 4886@deftypefun size_t __fbufsize (FILE *@var{stream})
d08a7e4c 4887@standards{GNU, stdio_ext.h}
171e9210 4888@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acsafe{}}
7b4161bb
UD
4889The @code{__fbufsize} function return the size of the buffer in the
4890stream @var{stream}. This value can be used to optimize the use of the
4891stream.
4892
4893This function is declared in the @file{stdio_ext.h} header.
4894@end deftypefun
4895
cc6e48bc 4896@deftypefun size_t __fpending (FILE *@var{stream})
d08a7e4c 4897@standards{GNU, stdio_ext.h}
171e9210 4898@safety{@prelim{}@mtsafe{@mtsrace{:stream}}@asunsafe{@asucorrupt{}}@acsafe{}}
cc6e48bc 4899The @code{__fpending}
f126ef67 4900function returns the number of bytes currently in the output buffer.
c703cd7a 4901For wide-oriented streams the measuring unit is wide characters. This
f126ef67 4902function should not be used on buffers in read mode or opened read-only.
7b4161bb
UD
4903
4904This function is declared in the @file{stdio_ext.h} header.
4905@end deftypefun
4906
28f540f4
RM
4907@node Other Kinds of Streams
4908@section Other Kinds of Streams
4909
1f77f049 4910@Theglibc{} provides ways for you to define additional kinds of
28f540f4
RM
4911streams that do not necessarily correspond to an open file.
4912
4913One such type of stream takes input from or writes output to a string.
4914These kinds of streams are used internally to implement the
4915@code{sprintf} and @code{sscanf} functions. You can also create such a
4916stream explicitly, using the functions described in @ref{String Streams}.
4917
4918More generally, you can define streams that do input/output to arbitrary
4919objects using functions supplied by your program. This protocol is
4920discussed in @ref{Custom Streams}.
4921
4922@strong{Portability Note:} The facilities described in this section are
4923specific to GNU. Other systems or C implementations might or might not
4924provide equivalent functionality.
4925
4926@menu
19c3f208 4927* String Streams:: Streams that get data from or put data in
162ba701 4928 a string or memory buffer.
28f540f4 4929* Custom Streams:: Defining your own streams with an arbitrary
162ba701 4930 input data source and/or output data sink.
28f540f4
RM
4931@end menu
4932
4933@node String Streams
4934@subsection String Streams
4935
4936@cindex stream, for I/O to a string
4937@cindex string stream
4938The @code{fmemopen} and @code{open_memstream} functions allow you to do
4939I/O to a string or memory buffer. These facilities are declared in
4940@file{stdio.h}.
4941@pindex stdio.h
4942
28f540f4 4943@deftypefun {FILE *} fmemopen (void *@var{buf}, size_t @var{size}, const char *@var{opentype})
d08a7e4c 4944@standards{GNU, stdio.h}
171e9210
AO
4945@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
4946@c Unlike open_memstream, fmemopen does (indirectly) call _IO_link_in,
4947@c bringing with it additional potential for async trouble with
4948@c list_all_lock.
28f540f4
RM
4949This function opens a stream that allows the access specified by the
4950@var{opentype} argument, that reads from or writes to the buffer specified
4951by the argument @var{buf}. This array must be at least @var{size} bytes long.
4952
4953If you specify a null pointer as the @var{buf} argument, @code{fmemopen}
04b9968b
UD
4954dynamically allocates an array @var{size} bytes long (as with @code{malloc};
4955@pxref{Unconstrained Allocation}). This is really only useful
28f540f4
RM
4956if you are going to write things to the buffer and then read them back
4957in again, because you have no way of actually getting a pointer to the
4958buffer (for this, try @code{open_memstream}, below). The buffer is
417d6b34 4959freed when the stream is closed.
28f540f4
RM
4960
4961The argument @var{opentype} is the same as in @code{fopen}
8b7fb588 4962(@pxref{Opening Streams}). If the @var{opentype} specifies
28f540f4
RM
4963append mode, then the initial file position is set to the first null
4964character in the buffer. Otherwise the initial file position is at the
4965beginning of the buffer.
4966
4967When a stream open for writing is flushed or closed, a null character
4968(zero byte) is written at the end of the buffer if it fits. You
4969should add an extra byte to the @var{size} argument to account for this.
4970Attempts to write more than @var{size} bytes to the buffer result
4971in an error.
4972
4973For a stream open for reading, null characters (zero bytes) in the
4974buffer do not count as ``end of file''. Read operations indicate end of
4975file only when the file position advances past @var{size} bytes. So, if
4976you want to read characters from a null-terminated string, you should
4977supply the length of the string as the @var{size} argument.
4978@end deftypefun
4979
4980Here is an example of using @code{fmemopen} to create a stream for
4981reading from a string:
4982
4983@smallexample
4984@include memopen.c.texi
4985@end smallexample
4986
4987This program produces the following output:
4988
4989@smallexample
4990Got f
4991Got o
4992Got o
4993Got b
4994Got a
4995Got r
4996@end smallexample
4997
28f540f4 4998@deftypefun {FILE *} open_memstream (char **@var{ptr}, size_t *@var{sizeloc})
d08a7e4c 4999@standards{GNU, stdio.h}
171e9210 5000@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{}}@acunsafe{@acsmem{}}}
28f540f4 5001This function opens a stream for writing to a buffer. The buffer is
29402b12
RM
5002allocated dynamically and grown as necessary, using @code{malloc}.
5003After you've closed the stream, this buffer is your responsibility to
5004clean up using @code{free} or @code{realloc}. @xref{Unconstrained Allocation}.
28f540f4
RM
5005
5006When the stream is closed with @code{fclose} or flushed with
5007@code{fflush}, the locations @var{ptr} and @var{sizeloc} are updated to
5008contain the pointer to the buffer and its size. The values thus stored
5009remain valid only as long as no further output on the stream takes
5010place. If you do more output, you must flush the stream again to store
5011new values before you use them again.
5012
5013A null character is written at the end of the buffer. This null character
5014is @emph{not} included in the size value stored at @var{sizeloc}.
5015
a5a0310d
UD
5016You can move the stream's file position with @code{fseek} or
5017@code{fseeko} (@pxref{File Positioning}). Moving the file position past
5018the end of the data already written fills the intervening space with
5019zeroes.
28f540f4
RM
5020@end deftypefun
5021
5022Here is an example of using @code{open_memstream}:
5023
5024@smallexample
5025@include memstrm.c.texi
5026@end smallexample
5027
5028This program produces the following output:
5029
5030@smallexample
5031buf = `hello', size = 5
5032buf = `hello, world', size = 12
5033@end smallexample
5034
28f540f4
RM
5035@node Custom Streams
5036@subsection Programming Your Own Custom Streams
5037@cindex custom streams
5038@cindex programming your own streams
5039
5040This section describes how you can make a stream that gets input from an
5041arbitrary data source or writes output to an arbitrary data sink
52cea457
UD
5042programmed by you. We call these @dfn{custom streams}. The functions
5043and types described here are all GNU extensions.
28f540f4
RM
5044
5045@c !!! this does not talk at all about the higher-level hooks
5046
5047@menu
5048* Streams and Cookies:: The @dfn{cookie} records where to fetch or
162ba701 5049 store data that is read or written.
28f540f4 5050* Hook Functions:: How you should define the four @dfn{hook
162ba701 5051 functions} that a custom stream needs.
28f540f4
RM
5052@end menu
5053
5054@node Streams and Cookies
5055@subsubsection Custom Streams and Cookies
5056@cindex cookie, for custom stream
5057
5058Inside every custom stream is a special object called the @dfn{cookie}.
5059This is an object supplied by you which records where to fetch or store
5060the data read or written. It is up to you to define a data type to use
5061for the cookie. The stream functions in the library never refer
5062directly to its contents, and they don't even know what the type is;
5063they record its address with type @code{void *}.
5064
5065To implement a custom stream, you must specify @emph{how} to fetch or
5066store the data in the specified place. You do this by defining
5067@dfn{hook functions} to read, write, change ``file position'', and close
5068the stream. All four of these functions will be passed the stream's
5069cookie so they can tell where to fetch or store the data. The library
5070functions don't know what's inside the cookie, but your functions will
5071know.
5072
5073When you create a custom stream, you must specify the cookie pointer,
19c3f208 5074and also the four hook functions stored in a structure of type
28f540f4
RM
5075@code{cookie_io_functions_t}.
5076
5077These facilities are declared in @file{stdio.h}.
5078@pindex stdio.h
5079
28f540f4 5080@deftp {Data Type} {cookie_io_functions_t}
d08a7e4c 5081@standards{GNU, stdio.h}
19c3f208 5082This is a structure type that holds the functions that define the
28f540f4
RM
5083communications protocol between the stream and its cookie. It has
5084the following members:
5085
5086@table @code
5087@item cookie_read_function_t *read
5088This is the function that reads data from the cookie. If the value is a
f2ea0f5b 5089null pointer instead of a function, then read operations on this stream
28f540f4
RM
5090always return @code{EOF}.
5091
5092@item cookie_write_function_t *write
5093This is the function that writes data to the cookie. If the value is a
5094null pointer instead of a function, then data written to the stream is
5095discarded.
5096
5097@item cookie_seek_function_t *seek
5098This is the function that performs the equivalent of file positioning on
5099the cookie. If the value is a null pointer instead of a function, calls
a5a0310d
UD
5100to @code{fseek} or @code{fseeko} on this stream can only seek to
5101locations within the buffer; any attempt to seek outside the buffer will
5102return an @code{ESPIPE} error.
28f540f4
RM
5103
5104@item cookie_close_function_t *close
5105This function performs any appropriate cleanup on the cookie when
5106closing the stream. If the value is a null pointer instead of a
5107function, nothing special is done to close the cookie when the stream is
5108closed.
5109@end table
5110@end deftp
5111
28f540f4 5112@deftypefun {FILE *} fopencookie (void *@var{cookie}, const char *@var{opentype}, cookie_io_functions_t @var{io-functions})
d08a7e4c 5113@standards{GNU, stdio.h}
171e9210 5114@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@acsmem{} @aculock{}}}
28f540f4
RM
5115This function actually creates the stream for communicating with the
5116@var{cookie} using the functions in the @var{io-functions} argument.
5117The @var{opentype} argument is interpreted as for @code{fopen};
5118see @ref{Opening Streams}. (But note that the ``truncate on
5119open'' option is ignored.) The new stream is fully buffered.
5120
5121The @code{fopencookie} function returns the newly created stream, or a null
5122pointer in case of an error.
5123@end deftypefun
5124
5125@node Hook Functions
5126@subsubsection Custom Stream Hook Functions
5127@cindex hook functions (of custom streams)
5128
5129Here are more details on how you should define the four hook functions
5130that a custom stream needs.
5131
5132You should define the function to read data from the cookie as:
5133
5134@smallexample
62ecda3d 5135ssize_t @var{reader} (void *@var{cookie}, char *@var{buffer}, size_t @var{size})
28f540f4
RM
5136@end smallexample
5137
5138This is very similar to the @code{read} function; see @ref{I/O
5139Primitives}. Your function should transfer up to @var{size} bytes into
5140the @var{buffer}, and return the number of bytes read, or zero to
5141indicate end-of-file. You can return a value of @code{-1} to indicate
5142an error.
5143
5144You should define the function to write data to the cookie as:
5145
5146@smallexample
62ecda3d 5147ssize_t @var{writer} (void *@var{cookie}, const char *@var{buffer}, size_t @var{size})
28f540f4
RM
5148@end smallexample
5149
5150This is very similar to the @code{write} function; see @ref{I/O
5151Primitives}. Your function should transfer up to @var{size} bytes from
5152the buffer, and return the number of bytes written. You can return a
247c3ede
PB
5153value of @code{0} to indicate an error. You must not return any
5154negative value.
28f540f4
RM
5155
5156You should define the function to perform seek operations on the cookie
5157as:
5158
5159@smallexample
c1e36819 5160int @var{seeker} (void *@var{cookie}, off64_t *@var{position}, int @var{whence})
28f540f4
RM
5161@end smallexample
5162
5163For this function, the @var{position} and @var{whence} arguments are
c1e36819 5164interpreted as for @code{fgetpos}; see @ref{Portable Positioning}.
28f540f4 5165
19c3f208 5166After doing the seek operation, your function should store the resulting
28f540f4
RM
5167file position relative to the beginning of the file in @var{position}.
5168Your function should return a value of @code{0} on success and @code{-1}
5169to indicate an error.
5170
5171You should define the function to do cleanup operations on the cookie
5172appropriate for closing the stream as:
5173
5174@smallexample
5175int @var{cleaner} (void *@var{cookie})
5176@end smallexample
5177
5178Your function should return @code{-1} to indicate an error, and @code{0}
5179otherwise.
5180
fff763a5 5181@deftp {Data Type} cookie_read_function_t
d08a7e4c 5182@standards{GNU, stdio.h}
28f540f4
RM
5183This is the data type that the read function for a custom stream should have.
5184If you declare the function as shown above, this is the type it will have.
5185@end deftp
5186
fff763a5 5187@deftp {Data Type} cookie_write_function_t
d08a7e4c 5188@standards{GNU, stdio.h}
28f540f4
RM
5189The data type of the write function for a custom stream.
5190@end deftp
5191
fff763a5 5192@deftp {Data Type} cookie_seek_function_t
d08a7e4c 5193@standards{GNU, stdio.h}
28f540f4
RM
5194The data type of the seek function for a custom stream.
5195@end deftp
5196
fff763a5 5197@deftp {Data Type} cookie_close_function_t
d08a7e4c 5198@standards{GNU, stdio.h}
28f540f4
RM
5199The data type of the close function for a custom stream.
5200@end deftp
5201
5202@ignore
5203Roland says:
5204
5205@quotation
5206There is another set of functions one can give a stream, the
5207input-room and output-room functions. These functions must
5208understand stdio internals. To describe how to use these
5209functions, you also need to document lots of how stdio works
5210internally (which isn't relevant for other uses of stdio).
5211Perhaps I can write an interface spec from which you can write
5212good documentation. But it's pretty complex and deals with lots
5213of nitty-gritty details. I think it might be better to let this
5214wait until the rest of the manual is more done and polished.
5215@end quotation
5216@end ignore
5217
5218@c ??? This section could use an example.
0501d603
UD
5219
5220
5221@node Formatted Messages
5222@section Formatted Messages
5223@cindex formatted messages
5224
5225On systems which are based on System V messages of programs (especially
5226the system tools) are printed in a strict form using the @code{fmtmsg}
5227function. The uniformity sometimes helps the user to interpret messages
cf29ffbe 5228and the strictness tests of the @code{fmtmsg} function ensure that the
0501d603
UD
5229programmer follows some minimal requirements.
5230
5231@menu
5232* Printing Formatted Messages:: The @code{fmtmsg} function.
5233* Adding Severity Classes:: Add more severity classes.
5234* Example:: How to use @code{fmtmsg} and @code{addseverity}.
5235@end menu
5236
5237
5238@node Printing Formatted Messages
5239@subsection Printing Formatted Messages
5240
5241Messages can be printed to standard error and/or to the console. To
cf29ffbe 5242select the destination the programmer can use the following two values,
0501d603
UD
5243bitwise OR combined if wanted, for the @var{classification} parameter of
5244@code{fmtmsg}:
5245
5246@vtable @code
5247@item MM_PRINT
5248Display the message in standard error.
5249@item MM_CONSOLE
5250Display the message on the system console.
5251@end vtable
5252
f2ea0f5b 5253The erroneous piece of the system can be signalled by exactly one of the
0501d603
UD
5254following values which also is bitwise ORed with the
5255@var{classification} parameter to @code{fmtmsg}:
5256
5257@vtable @code
5258@item MM_HARD
5259The source of the condition is some hardware.
5260@item MM_SOFT
5261The source of the condition is some software.
5262@item MM_FIRM
5263The source of the condition is some firmware.
5264@end vtable
5265
5266A third component of the @var{classification} parameter to @code{fmtmsg}
5267can describe the part of the system which detects the problem. This is
5268done by using exactly one of the following values:
5269
5270@vtable @code
5271@item MM_APPL
f2ea0f5b 5272The erroneous condition is detected by the application.
0501d603 5273@item MM_UTIL
f2ea0f5b 5274The erroneous condition is detected by a utility.
0501d603 5275@item MM_OPSYS
f2ea0f5b 5276The erroneous condition is detected by the operating system.
0501d603
UD
5277@end vtable
5278
5279A last component of @var{classification} can signal the results of this
5280message. Exactly one of the following values can be used:
5281
5282@vtable @code
5283@item MM_RECOVER
5284It is a recoverable error.
5285@item MM_NRECOV
5286It is a non-recoverable error.
5287@end vtable
5288
0501d603 5289@deftypefun int fmtmsg (long int @var{classification}, const char *@var{label}, int @var{severity}, const char *@var{text}, const char *@var{action}, const char *@var{tag})
d08a7e4c 5290@standards{XPG, fmtmsg.h}
171e9210 5291@safety{@prelim{}@mtsafe{}@asunsafe{@asulock{}}@acsafe{}}
0501d603
UD
5292Display a message described by its parameters on the device(s) specified
5293in the @var{classification} parameter. The @var{label} parameter
5294identifies the source of the message. The string should consist of two
5295colon separated parts where the first part has not more than 10 and the
04b9968b 5296second part not more than 14 characters. The @var{text} parameter
f2ea0f5b 5297describes the condition of the error, the @var{action} parameter possible
0501d603
UD
5298steps to recover from the error and the @var{tag} parameter is a
5299reference to the online documentation where more information can be
5300found. It should contain the @var{label} value and a unique
5301identification number.
5302
cf29ffbe 5303Each of the parameters can be a special value which means this value
0501d603
UD
5304is to be omitted. The symbolic names for these values are:
5305
5306@vtable @code
5307@item MM_NULLLBL
5308Ignore @var{label} parameter.
5309@item MM_NULLSEV
5310Ignore @var{severity} parameter.
5311@item MM_NULLMC
5312Ignore @var{classification} parameter. This implies that nothing is
5313actually printed.
5314@item MM_NULLTXT
5315Ignore @var{text} parameter.
5316@item MM_NULLACT
5317Ignore @var{action} parameter.
5318@item MM_NULLTAG
5319Ignore @var{tag} parameter.
5320@end vtable
5321
cf29ffbe 5322There is another way certain fields can be omitted from the output to
0501d603 5323standard error. This is described below in the description of
0bc93a2f 5324environment variables influencing the behavior.
0501d603
UD
5325
5326The @var{severity} parameter can have one of the values in the following
5327table:
5328@cindex severity class
5329
5330@vtable @code
5331@item MM_NOSEV
5332Nothing is printed, this value is the same as @code{MM_NULLSEV}.
5333@item MM_HALT
5334This value is printed as @code{HALT}.
5335@item MM_ERROR
5336This value is printed as @code{ERROR}.
5337@item MM_WARNING
5338This value is printed as @code{WARNING}.
5339@item MM_INFO
5340This value is printed as @code{INFO}.
5341@end vtable
5342
5343The numeric value of these five macros are between @code{0} and
5344@code{4}. Using the environment variable @code{SEV_LEVEL} or using the
5345@code{addseverity} function one can add more severity levels with their
5346corresponding string to print. This is described below
5347(@pxref{Adding Severity Classes}).
5348
5349@noindent
5350If no parameter is ignored the output looks like this:
5351
5352@smallexample
5353@var{label}: @var{severity-string}: @var{text}
5354TO FIX: @var{action} @var{tag}
5355@end smallexample
5356
5357The colons, new line characters and the @code{TO FIX} string are
5358inserted if necessary, i.e., if the corresponding parameter is not
5359ignored.
5360
5361This function is specified in the X/Open Portability Guide. It is also
04b9968b 5362available on all systems derived from System V.
0501d603 5363
cf29ffbe 5364The function returns the value @code{MM_OK} if no error occurred. If
0501d603
UD
5365only the printing to standard error failed, it returns @code{MM_NOMSG}.
5366If printing to the console fails, it returns @code{MM_NOCON}. If
cf29ffbe 5367nothing is printed @code{MM_NOTOK} is returned. Among situations where
0501d603
UD
5368all outputs fail this last value is also returned if a parameter value
5369is incorrect.
5370@end deftypefun
5371
0bc93a2f 5372There are two environment variables which influence the behavior of
0501d603
UD
5373@code{fmtmsg}. The first is @code{MSGVERB}. It is used to control the
5374output actually happening on standard error (@emph{not} the console
04b9968b 5375output). Each of the five fields can explicitly be enabled. To do
0501d603 5376this the user has to put the @code{MSGVERB} variable with a format like
cf29ffbe 5377the following in the environment before calling the @code{fmtmsg} function
0501d603
UD
5378the first time:
5379
5380@smallexample
95fdc6a0 5381MSGVERB=@var{keyword}[:@var{keyword}[:@dots{}]]
0501d603
UD
5382@end smallexample
5383
5384Valid @var{keyword}s are @code{label}, @code{severity}, @code{text},
5385@code{action}, and @code{tag}. If the environment variable is not given
5386or is the empty string, a not supported keyword is given or the value is
5387somehow else invalid, no part of the message is masked out.
5388
0bc93a2f 5389The second environment variable which influences the behavior of
0501d603 5390@code{fmtmsg} is @code{SEV_LEVEL}. This variable and the change in the
0bc93a2f 5391behavior of @code{fmtmsg} is not specified in the X/Open Portability
0501d603 5392Guide. It is available in System V systems, though. It can be used to
cf29ffbe 5393introduce new severity levels. By default, only the five severity levels
0501d603
UD
5394described above are available. Any other numeric value would make
5395@code{fmtmsg} print nothing.
5396
5397If the user puts @code{SEV_LEVEL} with a format like
5398
5399@smallexample
95fdc6a0 5400SEV_LEVEL=[@var{description}[:@var{description}[:@dots{}]]]
0501d603
UD
5401@end smallexample
5402
5403@noindent
5404in the environment of the process before the first call to
5405@code{fmtmsg}, where @var{description} has a value of the form
5406
5407@smallexample
5408@var{severity-keyword},@var{level},@var{printstring}
5409@end smallexample
5410
5411The @var{severity-keyword} part is not used by @code{fmtmsg} but it has
5412to be present. The @var{level} part is a string representation of a
5413number. The numeric value must be a number greater than 4. This value
5414must be used in the @var{severity} parameter of @code{fmtmsg} to select
5415this class. It is not possible to overwrite any of the predefined
5416classes. The @var{printstring} is the string printed when a message of
5417this class is processed by @code{fmtmsg} (see above, @code{fmtsmg} does
5418not print the numeric value but instead the string representation).
5419
5420
5421@node Adding Severity Classes
5422@subsection Adding Severity Classes
5423@cindex severity class
5424
04b9968b 5425There is another possibility to introduce severity classes besides using
0501d603
UD
5426the environment variable @code{SEV_LEVEL}. This simplifies the task of
5427introducing new classes in a running program. One could use the
5428@code{setenv} or @code{putenv} function to set the environment variable,
cf29ffbe 5429but this is toilsome.
0501d603
UD
5430
5431@deftypefun int addseverity (int @var{severity}, const char *@var{string})
171e9210 5432@safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsmem{}}}
04b9968b 5433This function allows the introduction of new severity classes which can be
0501d603
UD
5434addressed by the @var{severity} parameter of the @code{fmtmsg} function.
5435The @var{severity} parameter of @code{addseverity} must match the value
04b9968b 5436for the parameter with the same name of @code{fmtmsg}, and @var{string}
0501d603
UD
5437is the string printed in the actual messages instead of the numeric
5438value.
5439
5440If @var{string} is @code{NULL} the severity class with the numeric value
5441according to @var{severity} is removed.
5442
cf29ffbe
UD
5443It is not possible to overwrite or remove one of the default severity
5444classes. All calls to @code{addseverity} with @var{severity} set to one
5445of the values for the default classes will fail.
5446
0501d603
UD
5447The return value is @code{MM_OK} if the task was successfully performed.
5448If the return value is @code{MM_NOTOK} something went wrong. This could
5449mean that no more memory is available or a class is not available when
5450it has to be removed.
5451
5452This function is not specified in the X/Open Portability Guide although
cf29ffbe 5453the @code{fmtsmg} function is. It is available on System V systems.
0501d603
UD
5454@end deftypefun
5455
5456
5457@node Example
5458@subsection How to use @code{fmtmsg} and @code{addseverity}
5459
c703cd7a 5460Here is a simple example program to illustrate the use of both
0501d603
UD
5461functions described in this section.
5462
5463@smallexample
5464@include fmtmsgexpl.c.texi
5465@end smallexample
5466
04b9968b
UD
5467The second call to @code{fmtmsg} illustrates a use of this function as
5468it usually occurs on System V systems, which heavily use this function.
5469It seems worthwhile to give a short explanation here of how this system
5470works on System V. The value of the
0bc93a2f 5471@var{label} field (@code{UX:cat}) says that the error occurred in the
0501d603
UD
5472Unix program @code{cat}. The explanation of the error follows and the
5473value for the @var{action} parameter is @code{"refer to manual"}. One
04b9968b 5474could be more specific here, if necessary. The @var{tag} field contains,
0501d603
UD
5475as proposed above, the value of the string given for the @var{label}
5476parameter, and additionally a unique ID (@code{001} in this case). For
5477a GNU environment this string could contain a reference to the
5478corresponding node in the Info page for the program.
5479
5480@noindent
5481Running this program without specifying the @code{MSGVERB} and
5482@code{SEV_LEVEL} function produces the following output:
5483
5484@smallexample
5485UX:cat: NOTE2: invalid syntax
5486TO FIX: refer to manual UX:cat:001
5487@end smallexample
5488
5489We see the different fields of the message and how the extra glue (the
c703cd7a 5490colons and the @code{TO FIX} string) is printed. But only one of the
0501d603
UD
5491three calls to @code{fmtmsg} produced output. The first call does not
5492print anything because the @var{label} parameter is not in the correct
8b7fb588
UD
5493form. The string must contain two fields, separated by a colon
5494(@pxref{Printing Formatted Messages}). The third @code{fmtmsg} call
0501d603
UD
5495produced no output since the class with the numeric value @code{6} is
5496not defined. Although a class with numeric value @code{5} is also not
04b9968b 5497defined by default, the call to @code{addseverity} introduces it and
0ea554bf 5498the second call to @code{fmtmsg} produces the above output.
0501d603
UD
5499
5500When we change the environment of the program to contain
5501@code{SEV_LEVEL=XXX,6,NOTE} when running it we get a different result:
5502
5503@smallexample
5504UX:cat: NOTE2: invalid syntax
5505TO FIX: refer to manual UX:cat:001
5506label:foo: NOTE: text
5507TO FIX: action tag
5508@end smallexample
5509
04b9968b 5510Now the third call to @code{fmtmsg} produced some output and we see how
0501d603
UD
5511the string @code{NOTE} from the environment variable appears in the
5512message.
5513
04b9968b 5514Now we can reduce the output by specifying which fields we are
0501d603
UD
5515interested in. If we additionally set the environment variable
5516@code{MSGVERB} to the value @code{severity:label:action} we get the
5517following output:
5518
5519@smallexample
5520UX:cat: NOTE2
5521TO FIX: refer to manual
5522label:foo: NOTE
5523TO FIX: action
5524@end smallexample
5525
5526@noindent
5527I.e., the output produced by the @var{text} and the @var{tag} parameters
cf29ffbe 5528to @code{fmtmsg} vanished. Please also note that now there is no colon
0501d603 5529after the @code{NOTE} and @code{NOTE2} strings in the output. This is
04b9968b 5530not necessary since there is no more output on this line because the text
0501d603 5531is missing.