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