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