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