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