Update.
[glibc.git] / manual / stdio.texi
blob0b030cf2d8eb445bbd2facb8fd393e5a9808b1bf
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 * Simple Output::               Unformatted output by characters and lines.
21 * Character Input::             Unformatted input by characters and words.
22 * Line Input::                  Reading a line or a record from a stream.
23 * Unreading::                   Peeking ahead/pushing back input just read.
24 * Block Input/Output::          Input and output operations on blocks of data.
25 * Formatted Output::            @code{printf} and related functions.
26 * Customizing Printf::          You can define new conversion specifiers for
27                                  @code{printf} and friends.
28 * Formatted Input::             @code{scanf} and related functions.
29 * EOF and Errors::              How you can tell if an I/O error happens.
30 * Error Recovery::              What you can do about errors.
31 * Binary Streams::              Some systems distinguish between text files
32                                  and binary files.
33 * File Positioning::            About random-access streams.
34 * Portable Positioning::        Random access on peculiar ISO C systems.
35 * Stream Buffering::            How to control buffering of streams.
36 * Other Kinds of Streams::      Streams that do not necessarily correspond
37                                  to an open file.
38 * Formatted Messages::          Print strictly formatted messages.
39 @end menu
41 @node Streams
42 @section Streams
44 For historical reasons, the type of the C data structure that represents
45 a stream is called @code{FILE} rather than ``stream''.  Since most of
46 the library functions deal with objects of type @code{FILE *}, sometimes
47 the term @dfn{file pointer} is also used to mean ``stream''.  This leads
48 to unfortunate confusion over terminology in many books on C.  This
49 manual, however, is careful to use the terms ``file'' and ``stream''
50 only in the technical sense.
51 @cindex file pointer
53 @pindex stdio.h
54 The @code{FILE} type is declared in the header file @file{stdio.h}.
56 @comment stdio.h
57 @comment ISO
58 @deftp {Data Type} FILE
59 This is the data type used to represent stream objects.  A @code{FILE}
60 object holds all of the internal state information about the connection
61 to the associated file, including such things as the file position
62 indicator and buffering information.  Each stream also has error and
63 end-of-file status indicators that can be tested with the @code{ferror}
64 and @code{feof} functions; see @ref{EOF and Errors}.
65 @end deftp
67 @code{FILE} objects are allocated and managed internally by the
68 input/output library functions.  Don't try to create your own objects of
69 type @code{FILE}; let the library do it.  Your programs should
70 deal only with pointers to these objects (that is, @code{FILE *} values)
71 rather than the objects themselves.
72 @c !!! should say that FILE's have "No user-serviceable parts inside."
74 @node Standard Streams
75 @section Standard Streams
76 @cindex standard streams
77 @cindex streams, standard
79 When the @code{main} function of your program is invoked, it already has
80 three predefined streams open and available for use.  These represent
81 the ``standard'' input and output channels that have been established
82 for the process.
84 These streams are declared in the header file @file{stdio.h}.
85 @pindex stdio.h
87 @comment stdio.h
88 @comment ISO
89 @deftypevar {FILE *} stdin
90 The @dfn{standard input} stream, which is the normal source of input for the
91 program.
92 @end deftypevar
93 @cindex standard input stream
95 @comment stdio.h
96 @comment ISO
97 @deftypevar {FILE *} stdout
98 The @dfn{standard output} stream, which is used for normal output from
99 the program.
100 @end deftypevar
101 @cindex standard output stream
103 @comment stdio.h
104 @comment ISO
105 @deftypevar {FILE *} stderr
106 The @dfn{standard error} stream, which is used for error messages and
107 diagnostics issued by the program.
108 @end deftypevar
109 @cindex standard error stream
111 In the GNU system, you can specify what files or processes correspond to
112 these streams using the pipe and redirection facilities provided by the
113 shell.  (The primitives shells use to implement these facilities are
114 described in @ref{File System Interface}.)  Most other operating systems
115 provide similar mechanisms, but the details of how to use them can vary.
117 In the GNU C library, @code{stdin}, @code{stdout}, and @code{stderr} are
118 normal variables which you can set just like any others.  For example, to redirect
119 the standard output to a file, you could do:
121 @smallexample
122 fclose (stdout);
123 stdout = fopen ("standard-output-file", "w");
124 @end smallexample
126 Note however, that in other systems @code{stdin}, @code{stdout}, and
127 @code{stderr} are macros that you cannot assign to in the normal way.
128 But you can use @code{freopen} to get the effect of closing one and
129 reopening it.  @xref{Opening Streams}.
131 @node Opening Streams
132 @section Opening Streams
134 @cindex opening a stream
135 Opening a file with the @code{fopen} function creates a new stream and
136 establishes a connection between the stream and a file.  This may
137 involve creating a new file.
139 @pindex stdio.h
140 Everything described in this section is declared in the header file
141 @file{stdio.h}.
143 @comment stdio.h
144 @comment ISO
145 @deftypefun {FILE *} fopen (const char *@var{filename}, const char *@var{opentype})
146 The @code{fopen} function opens a stream for I/O to the file
147 @var{filename}, and returns a pointer to the stream.
149 The @var{opentype} argument is a string that controls how the file is
150 opened and specifies attributes of the resulting stream.  It must begin
151 with one of the following sequences of characters:
153 @table @samp
154 @item r
155 Open an existing file for reading only.
157 @item w
158 Open the file for writing only.  If the file already exists, it is
159 truncated to zero length.  Otherwise a new file is created.
161 @item a
162 Open a file for append access; that is, writing at the end of file only.
163 If the file already exists, its initial contents are unchanged and
164 output to the stream is appended to the end of the file.
165 Otherwise, a new, empty file is created.
167 @item r+
168 Open an existing file for both reading and writing.  The initial contents
169 of the file are unchanged and the initial file position is at the
170 beginning of the file.
172 @item w+
173 Open a file for both reading and writing.  If the file already exists, it
174 is truncated to zero length.  Otherwise, a new file is created.
176 @item a+
177 Open or create file for both reading and appending.  If the file exists,
178 its initial contents are unchanged.  Otherwise, a new file is created.
179 The initial file position for reading is at the beginning of the file,
180 but output is always appended to the end of the file.
181 @end table
183 As you can see, @samp{+} requests a stream that can do both input and
184 output.  The ISO standard says that when using such a stream, you must
185 call @code{fflush} (@pxref{Stream Buffering}) or a file positioning
186 function such as @code{fseek} (@pxref{File Positioning}) when switching
187 from reading to writing or vice versa.  Otherwise, internal buffers
188 might not be emptied properly.  The GNU C library does not have this
189 limitation; you can do arbitrary reading and writing operations on a
190 stream in whatever order.
192 Additional characters may appear after these to specify flags for the
193 call.  Always put the mode (@samp{r}, @samp{w+}, etc.) first; that is
194 the only part you are guaranteed will be understood by all systems.
196 The GNU C library defines one additional character for use in
197 @var{opentype}: the character @samp{x} insists on creating a new
198 file---if a file @var{filename} already exists, @code{fopen} fails
199 rather than opening it.  If you use @samp{x} you are guaranteed that
200 you will not clobber an existing file.  This is equivalent to the
201 @code{O_EXCL} option to the @code{open} function (@pxref{Opening and
202 Closing Files}).
204 The character @samp{b} in @var{opentype} has a standard meaning; it
205 requests a binary stream rather than a text stream.  But this makes no
206 difference in POSIX systems (including the GNU system).  If both
207 @samp{+} and @samp{b} are specified, they can appear in either order.
208 @xref{Binary Streams}.
210 @cindex stream orientation
211 @cindex orientation, stream
212 If the @var{opentype} string contains the sequence
213 @code{,ccs=@var{STRING}} then @var{STRING} is taken as the name of a
214 coded character set and @code{fopen} will mark the stream as
215 wide-oriented which appropriate conversion functions in place to convert
216 from and to the character set @var{STRING} is place.  Any other stream
217 is opened initially unoriented and the orientation is decided with the
218 first file operation.  If the first operation is a wide character
219 operation, the stream is not only marked as wide-oriented, also the
220 conversion functions to convert to the coded character set used for the
221 current locale are loaded.  This will not change anymore from this point
222 on even if the locale selected for the @code{LC_CTYPE} category is
223 changed.
225 Any other characters in @var{opentype} are simply ignored.  They may be
226 meaningful in other systems.
228 If the open fails, @code{fopen} returns a null pointer.
230 When the sources are compiling with @code{_FILE_OFFSET_BITS == 64} on a
231 32 bit machine this function is in fact @code{fopen64} since the LFS
232 interface replaces transparently the old interface.
233 @end deftypefun
235 You can have multiple streams (or file descriptors) pointing to the same
236 file open at the same time.  If you do only input, this works
237 straightforwardly, but you must be careful if any output streams are
238 included.  @xref{Stream/Descriptor Precautions}.  This is equally true
239 whether the streams are in one program (not usual) or in several
240 programs (which can easily happen).  It may be advantageous to use the
241 file locking facilities to avoid simultaneous access.  @xref{File
242 Locks}.
244 @comment stdio.h
245 @comment Unix98
246 @deftypefun {FILE *} fopen64 (const char *@var{filename}, const char *@var{opentype})
247 This function is similar to @code{fopen} but the stream it returns a
248 pointer for is opened using @code{open64}.  Therefore this stream can be
249 used even on files larger then @math{2^31} bytes on 32 bit machines.
251 Please note that the return type is still @code{FILE *}.  There is no
252 special @code{FILE} type for the LFS interface.
254 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
255 bits machine this function is available under the name @code{fopen}
256 and so transparently replaces the old interface.
257 @end deftypefun
259 @comment stdio.h
260 @comment ISO
261 @deftypevr Macro int FOPEN_MAX
262 The value of this macro is an integer constant expression that
263 represents the minimum number of streams that the implementation
264 guarantees can be open simultaneously.  You might be able to open more
265 than this many streams, but that is not guaranteed.  The value of this
266 constant is at least eight, which includes the three standard streams
267 @code{stdin}, @code{stdout}, and @code{stderr}.  In POSIX.1 systems this
268 value is determined by the @code{OPEN_MAX} parameter; @pxref{General
269 Limits}.  In BSD and GNU, it is controlled by the @code{RLIMIT_NOFILE}
270 resource limit; @pxref{Limits on Resources}.
271 @end deftypevr
273 @comment stdio.h
274 @comment ISO
275 @deftypefun {FILE *} freopen (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
276 This function is like a combination of @code{fclose} and @code{fopen}.
277 It first closes the stream referred to by @var{stream}, ignoring any
278 errors that are detected in the process.  (Because errors are ignored,
279 you should not use @code{freopen} on an output stream if you have
280 actually done any output using the stream.)  Then the file named by
281 @var{filename} is opened with mode @var{opentype} as for @code{fopen},
282 and associated with the same stream object @var{stream}.
284 If the operation fails, a null pointer is returned; otherwise,
285 @code{freopen} returns @var{stream}.
287 @code{freopen} has traditionally been used to connect a standard stream
288 such as @code{stdin} with a file of your own choice.  This is useful in
289 programs in which use of a standard stream for certain purposes is
290 hard-coded.  In the GNU C library, you can simply close the standard
291 streams and open new ones with @code{fopen}.  But other systems lack
292 this ability, so using @code{freopen} is more portable.
294 When the sources are compiling with @code{_FILE_OFFSET_BITS == 64} on a
295 32 bit machine this function is in fact @code{freopen64} since the LFS
296 interface replaces transparently the old interface.
297 @end deftypefun
299 @comment stdio.h
300 @comment Unix98
301 @deftypefun {FILE *} freopen64 (const char *@var{filename}, const char *@var{opentype}, FILE *@var{stream})
302 This function is similar to @code{freopen}.  The only difference is that
303 on 32 bit machine the stream returned is able to read beyond the
304 @math{2^31} bytes limits imposed by the normal interface.  It should be
305 noted that the stream pointed to by @var{stream} need not be opened
306 using @code{fopen64} or @code{freopen64} since its mode is not important
307 for this function.
309 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
310 bits machine this function is available under the name @code{freopen}
311 and so transparently replaces the old interface.
312 @end deftypefun
315 @node Closing Streams
316 @section Closing Streams
318 @cindex closing a stream
319 When a stream is closed with @code{fclose}, the connection between the
320 stream and the file is cancelled.  After you have closed a stream, you
321 cannot perform any additional operations on it.
323 @comment stdio.h
324 @comment ISO
325 @deftypefun int fclose (FILE *@var{stream})
326 This function causes @var{stream} to be closed and the connection to
327 the corresponding file to be broken.  Any buffered output is written
328 and any buffered input is discarded.  The @code{fclose} function returns
329 a value of @code{0} if the file was closed successfully, and @code{EOF}
330 if an error was detected.
332 It is important to check for errors when you call @code{fclose} to close
333 an output stream, because real, everyday errors can be detected at this
334 time.  For example, when @code{fclose} writes the remaining buffered
335 output, it might get an error because the disk is full.  Even if you
336 know the buffer is empty, errors can still occur when closing a file if
337 you are using NFS.
339 The function @code{fclose} is declared in @file{stdio.h}.
340 @end deftypefun
342 To close all streams currently available the GNU C Library provides
343 another function.
345 @comment stdio.h
346 @comment GNU
347 @deftypefun int fcloseall (void)
348 This function causes all open streams of the process to be closed and
349 the connection to corresponding files to be broken.  All buffered data
350 is written and any buffered input is discarded.  The @code{fcloseall}
351 function returns a value of @code{0} if all the files were closed
352 successfully, and @code{EOF} if an error was detected.
354 This function should be used only in special situations, e.g., when an
355 error occurred and the program must be aborted.  Normally each single
356 stream should be closed separately so that problems with individual
357 streams can be identified.  It is also problematic since the standard
358 streams (@pxref{Standard Streams}) will also be closed.
360 The function @code{fcloseall} is declared in @file{stdio.h}.
361 @end deftypefun
363 If the @code{main} function to your program returns, or if you call the
364 @code{exit} function (@pxref{Normal Termination}), all open streams are
365 automatically closed properly.  If your program terminates in any other
366 manner, such as by calling the @code{abort} function (@pxref{Aborting a
367 Program}) or from a fatal signal (@pxref{Signal Handling}), open streams
368 might not be closed properly.  Buffered output might not be flushed and
369 files may be incomplete.  For more information on buffering of streams,
370 see @ref{Stream Buffering}.
372 @node Simple Output
373 @section Simple Output by Characters or Lines
375 @cindex writing to a stream, by characters
376 This section describes functions for performing character- and
377 line-oriented output.
379 These functions are declared in the header file @file{stdio.h}.
380 @pindex stdio.h
382 @comment stdio.h
383 @comment ISO
384 @deftypefun int fputc (int @var{c}, FILE *@var{stream})
385 The @code{fputc} function converts the character @var{c} to type
386 @code{unsigned char}, and writes it to the stream @var{stream}.
387 @code{EOF} is returned if a write error occurs; otherwise the
388 character @var{c} is returned.
389 @end deftypefun
391 @comment stdio.h
392 @comment ISO
393 @deftypefun int putc (int @var{c}, FILE *@var{stream})
394 This is just like @code{fputc}, except that most systems implement it as
395 a macro, making it faster.  One consequence is that it may evaluate the
396 @var{stream} argument more than once, which is an exception to the
397 general rule for macros.  @code{putc} is usually the best function to
398 use for writing a single character.
399 @end deftypefun
401 @comment stdio.h
402 @comment ISO
403 @deftypefun int putchar (int @var{c})
404 The @code{putchar} function is equivalent to @code{putc} with
405 @code{stdout} as the value of the @var{stream} argument.
406 @end deftypefun
408 @comment stdio.h
409 @comment ISO
410 @deftypefun int fputs (const char *@var{s}, FILE *@var{stream})
411 The function @code{fputs} writes the string @var{s} to the stream
412 @var{stream}.  The terminating null character is not written.
413 This function does @emph{not} add a newline character, either.
414 It outputs only the characters in the string.
416 This function returns @code{EOF} if a write error occurs, and otherwise
417 a non-negative value.
419 For example:
421 @smallexample
422 fputs ("Are ", stdout);
423 fputs ("you ", stdout);
424 fputs ("hungry?\n", stdout);
425 @end smallexample
427 @noindent
428 outputs the text @samp{Are you hungry?} followed by a newline.
429 @end deftypefun
431 @comment stdio.h
432 @comment ISO
433 @deftypefun int puts (const char *@var{s})
434 The @code{puts} function writes the string @var{s} to the stream
435 @code{stdout} followed by a newline.  The terminating null character of
436 the string is not written.  (Note that @code{fputs} does @emph{not}
437 write a newline as this function does.)
439 @code{puts} is the most convenient function for printing simple
440 messages.  For example:
442 @smallexample
443 puts ("This is a message.");
444 @end smallexample
446 @noindent
447 outputs the text @samp{This is a message.} followed by a newline.
448 @end deftypefun
450 @comment stdio.h
451 @comment SVID
452 @deftypefun int putw (int @var{w}, FILE *@var{stream})
453 This function writes the word @var{w} (that is, an @code{int}) to
454 @var{stream}.  It is provided for compatibility with SVID, but we
455 recommend you use @code{fwrite} instead (@pxref{Block Input/Output}).
456 @end deftypefun
458 @node Character Input
459 @section Character Input
461 @cindex reading from a stream, by characters
462 This section describes functions for performing character-oriented input.
463 These functions are declared in the header file @file{stdio.h}.
464 @pindex stdio.h
466 These functions return an @code{int} value that is either a character of
467 input, or the special value @code{EOF} (usually -1).  It is important to
468 store the result of these functions in a variable of type @code{int}
469 instead of @code{char}, even when you plan to use it only as a
470 character.  Storing @code{EOF} in a @code{char} variable truncates its
471 value to the size of a character, so that it is no longer
472 distinguishable from the valid character @samp{(char) -1}.  So always
473 use an @code{int} for the result of @code{getc} and friends, and check
474 for @code{EOF} after the call; once you've verified that the result is
475 not @code{EOF}, you can be sure that it will fit in a @samp{char}
476 variable without loss of information.
478 @comment stdio.h
479 @comment ISO
480 @deftypefun int fgetc (FILE *@var{stream})
481 This function reads the next character as an @code{unsigned char} from
482 the stream @var{stream} and returns its value, converted to an
483 @code{int}.  If an end-of-file condition or read error occurs,
484 @code{EOF} is returned instead.
485 @end deftypefun
487 @comment stdio.h
488 @comment ISO
489 @deftypefun int getc (FILE *@var{stream})
490 This is just like @code{fgetc}, except that it is permissible (and
491 typical) for it to be implemented as a macro that evaluates the
492 @var{stream} argument more than once.  @code{getc} is often highly
493 optimized, so it is usually the best function to use to read a single
494 character.
495 @end deftypefun
497 @comment stdio.h
498 @comment ISO
499 @deftypefun int getchar (void)
500 The @code{getchar} function is equivalent to @code{getc} with @code{stdin}
501 as the value of the @var{stream} argument.
502 @end deftypefun
504 Here is an example of a function that does input using @code{fgetc}.  It
505 would work just as well using @code{getc} instead, or using
506 @code{getchar ()} instead of @w{@code{fgetc (stdin)}}.
508 @smallexample
510 y_or_n_p (const char *question)
512   fputs (question, stdout);
513   while (1)
514     @{
515       int c, answer;
516       /* @r{Write a space to separate answer from question.} */
517       fputc (' ', stdout);
518       /* @r{Read the first character of the line.}
519          @r{This should be the answer character, but might not be.} */
520       c = tolower (fgetc (stdin));
521       answer = c;
522       /* @r{Discard rest of input line.} */
523       while (c != '\n' && c != EOF)
524         c = fgetc (stdin);
525       /* @r{Obey the answer if it was valid.} */
526       if (answer == 'y')
527         return 1;
528       if (answer == 'n')
529         return 0;
530       /* @r{Answer was invalid: ask for valid answer.} */
531       fputs ("Please answer y or n:", stdout);
532     @}
534 @end smallexample
536 @comment stdio.h
537 @comment SVID
538 @deftypefun int getw (FILE *@var{stream})
539 This function reads a word (that is, an @code{int}) from @var{stream}.
540 It's provided for compatibility with SVID.  We recommend you use
541 @code{fread} instead (@pxref{Block Input/Output}).  Unlike @code{getc},
542 any @code{int} value could be a valid result.  @code{getw} returns
543 @code{EOF} when it encounters end-of-file or an error, but there is no
544 way to distinguish this from an input word with value -1.
545 @end deftypefun
547 @node Line Input
548 @section Line-Oriented Input
550 Since many programs interpret input on the basis of lines, it's
551 convenient to have functions to read a line of text from a stream.
553 Standard C has functions to do this, but they aren't very safe: null
554 characters and even (for @code{gets}) long lines can confuse them.  So
555 the GNU library provides the nonstandard @code{getline} function that
556 makes it easy to read lines reliably.
558 Another GNU extension, @code{getdelim}, generalizes @code{getline}.  It
559 reads a delimited record, defined as everything through the next
560 occurrence of a specified delimiter character.
562 All these functions are declared in @file{stdio.h}.
564 @comment stdio.h
565 @comment GNU
566 @deftypefun ssize_t getline (char **@var{lineptr}, size_t *@var{n}, FILE *@var{stream})
567 This function reads an entire line from @var{stream}, storing the text
568 (including the newline and a terminating null character) in a buffer
569 and storing the buffer address in @code{*@var{lineptr}}.
571 Before calling @code{getline}, you should place in @code{*@var{lineptr}}
572 the address of a buffer @code{*@var{n}} bytes long, allocated with
573 @code{malloc}.  If this buffer is long enough to hold the line,
574 @code{getline} stores the line in this buffer.  Otherwise,
575 @code{getline} makes the buffer bigger using @code{realloc}, storing the
576 new buffer address back in @code{*@var{lineptr}} and the increased size
577 back in @code{*@var{n}}.
578 @xref{Unconstrained Allocation}.
580 If you set @code{*@var{lineptr}} to a null pointer, and @code{*@var{n}}
581 to zero, before the call, then @code{getline} allocates the initial
582 buffer for you by calling @code{malloc}.
584 In either case, when @code{getline} returns,  @code{*@var{lineptr}} is
585 a @code{char *} which points to the text of the line.
587 When @code{getline} is successful, it returns the number of characters
588 read (including the newline, but not including the terminating null).
589 This value enables you to distinguish null characters that are part of
590 the line from the null character inserted as a terminator.
592 This function is a GNU extension, but it is the recommended way to read
593 lines from a stream.  The alternative standard functions are unreliable.
595 If an error occurs or end of file is reached, @code{getline} returns
596 @code{-1}.
597 @end deftypefun
599 @comment stdio.h
600 @comment GNU
601 @deftypefun ssize_t getdelim (char **@var{lineptr}, size_t *@var{n}, int @var{delimiter}, FILE *@var{stream})
602 This function is like @code{getline} except that the character which
603 tells it to stop reading is not necessarily newline.  The argument
604 @var{delimiter} specifies the delimiter character; @code{getdelim} keeps
605 reading until it sees that character (or end of file).
607 The text is stored in @var{lineptr}, including the delimiter character
608 and a terminating null.  Like @code{getline}, @code{getdelim} makes
609 @var{lineptr} bigger if it isn't big enough.
611 @code{getline} is in fact implemented in terms of @code{getdelim}, just
612 like this:
614 @smallexample
615 ssize_t
616 getline (char **lineptr, size_t *n, FILE *stream)
618   return getdelim (lineptr, n, '\n', stream);
620 @end smallexample
621 @end deftypefun
623 @comment stdio.h
624 @comment ISO
625 @deftypefun {char *} fgets (char *@var{s}, int @var{count}, FILE *@var{stream})
626 The @code{fgets} function reads characters from the stream @var{stream}
627 up to and including a newline character and stores them in the string
628 @var{s}, adding a null character to mark the end of the string.  You
629 must supply @var{count} characters worth of space in @var{s}, but the
630 number of characters read is at most @var{count} @minus{} 1.  The extra
631 character space is used to hold the null character at the end of the
632 string.
634 If the system is already at end of file when you call @code{fgets}, then
635 the contents of the array @var{s} are unchanged and a null pointer is
636 returned.  A null pointer is also returned if a read error occurs.
637 Otherwise, the return value is the pointer @var{s}.
639 @strong{Warning:}  If the input data has a null character, you can't tell.
640 So don't use @code{fgets} unless you know the data cannot contain a null.
641 Don't use it to read files edited by the user because, if the user inserts
642 a null character, you should either handle it properly or print a clear
643 error message.  We recommend using @code{getline} instead of @code{fgets}.
644 @end deftypefun
646 @comment stdio.h
647 @comment ISO
648 @deftypefn {Deprecated function} {char *} gets (char *@var{s})
649 The function @code{gets} reads characters from the stream @code{stdin}
650 up to the next newline character, and stores them in the string @var{s}.
651 The newline character is discarded (note that this differs from the
652 behavior of @code{fgets}, which copies the newline character into the
653 string).  If @code{gets} encounters a read error or end-of-file, it
654 returns a null pointer; otherwise it returns @var{s}.
656 @strong{Warning:} The @code{gets} function is @strong{very dangerous}
657 because it provides no protection against overflowing the string
658 @var{s}.  The GNU library includes it for compatibility only.  You
659 should @strong{always} use @code{fgets} or @code{getline} instead.  To
660 remind you of this, the linker (if using GNU @code{ld}) will issue a
661 warning whenever you use @code{gets}.
662 @end deftypefn
664 @node Unreading
665 @section Unreading
666 @cindex peeking at input
667 @cindex unreading characters
668 @cindex pushing input back
670 In parser programs it is often useful to examine the next character in
671 the input stream without removing it from the stream.  This is called
672 ``peeking ahead'' at the input because your program gets a glimpse of
673 the input it will read next.
675 Using stream I/O, you can peek ahead at input by first reading it and
676 then @dfn{unreading} it (also called  @dfn{pushing it back} on the stream).
677 Unreading a character makes it available to be input again from the stream,
678 by  the next call to @code{fgetc} or other input function on that stream.
680 @menu
681 * Unreading Idea::              An explanation of unreading with pictures.
682 * How Unread::                  How to call @code{ungetc} to do unreading.
683 @end menu
685 @node Unreading Idea
686 @subsection What Unreading Means
688 Here is a pictorial explanation of unreading.  Suppose you have a
689 stream reading a file that contains just six characters, the letters
690 @samp{foobar}.  Suppose you have read three characters so far.  The
691 situation looks like this:
693 @smallexample
694 f  o  o  b  a  r
695          ^
696 @end smallexample
698 @noindent
699 so the next input character will be @samp{b}.
701 @c @group   Invalid outside @example
702 If instead of reading @samp{b} you unread the letter @samp{o}, you get a
703 situation like this:
705 @smallexample
706 f  o  o  b  a  r
707          |
708       o--
709       ^
710 @end smallexample
712 @noindent
713 so that the next input characters will be @samp{o} and @samp{b}.
714 @c @end group
716 @c @group
717 If you unread @samp{9} instead of @samp{o}, you get this situation:
719 @smallexample
720 f  o  o  b  a  r
721          |
722       9--
723       ^
724 @end smallexample
726 @noindent
727 so that the next input characters will be @samp{9} and @samp{b}.
728 @c @end group
730 @node How Unread
731 @subsection Using @code{ungetc} To Do Unreading
733 The function to unread a character is called @code{ungetc}, because it
734 reverses the action of @code{getc}.
736 @comment stdio.h
737 @comment ISO
738 @deftypefun int ungetc (int @var{c}, FILE *@var{stream})
739 The @code{ungetc} function pushes back the character @var{c} onto the
740 input stream @var{stream}.  So the next input from @var{stream} will
741 read @var{c} before anything else.
743 If @var{c} is @code{EOF}, @code{ungetc} does nothing and just returns
744 @code{EOF}.  This lets you call @code{ungetc} with the return value of
745 @code{getc} without needing to check for an error from @code{getc}.
747 The character that you push back doesn't have to be the same as the last
748 character that was actually read from the stream.  In fact, it isn't
749 necessary to actually read any characters from the stream before
750 unreading them with @code{ungetc}!  But that is a strange way to write
751 a program; usually @code{ungetc} is used only to unread a character
752 that was just read from the same stream.
754 The GNU C library only supports one character of pushback---in other
755 words, it does not work to call @code{ungetc} twice without doing input
756 in between.  Other systems might let you push back multiple characters;
757 then reading from the stream retrieves the characters in the reverse
758 order that they were pushed.
760 Pushing back characters doesn't alter the file; only the internal
761 buffering for the stream is affected.  If a file positioning function
762 (such as @code{fseek}, @code{fseeko} or @code{rewind}; @pxref{File
763 Positioning}) is called, any pending pushed-back characters are
764 discarded.
766 Unreading a character on a stream that is at end of file clears the
767 end-of-file indicator for the stream, because it makes the character of
768 input available.  After you read that character, trying to read again
769 will encounter end of file.
770 @end deftypefun
772 Here is an example showing the use of @code{getc} and @code{ungetc} to
773 skip over whitespace characters.  When this function reaches a
774 non-whitespace character, it unreads that character to be seen again on
775 the next read operation on the stream.
777 @smallexample
778 #include <stdio.h>
779 #include <ctype.h>
781 void
782 skip_whitespace (FILE *stream)
784   int c;
785   do
786     /* @r{No need to check for @code{EOF} because it is not}
787        @r{@code{isspace}, and @code{ungetc} ignores @code{EOF}.}  */
788     c = getc (stream);
789   while (isspace (c));
790   ungetc (c, stream);
792 @end smallexample
794 @node Block Input/Output
795 @section Block Input/Output
797 This section describes how to do input and output operations on blocks
798 of data.  You can use these functions to read and write binary data, as
799 well as to read and write text in fixed-size blocks instead of by
800 characters or lines.
801 @cindex binary I/O to a stream
802 @cindex block I/O to a stream
803 @cindex reading from a stream, by blocks
804 @cindex writing to a stream, by blocks
806 Binary files are typically used to read and write blocks of data in the
807 same format as is used to represent the data in a running program.  In
808 other words, arbitrary blocks of memory---not just character or string
809 objects---can be written to a binary file, and meaningfully read in
810 again by the same program.
812 Storing data in binary form is often considerably more efficient than
813 using the formatted I/O functions.  Also, for floating-point numbers,
814 the binary form avoids possible loss of precision in the conversion
815 process.  On the other hand, binary files can't be examined or modified
816 easily using many standard file utilities (such as text editors), and
817 are not portable between different implementations of the language, or
818 different kinds of computers.
820 These functions are declared in @file{stdio.h}.
821 @pindex stdio.h
823 @comment stdio.h
824 @comment ISO
825 @deftypefun size_t fread (void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
826 This function reads up to @var{count} objects of size @var{size} into
827 the array @var{data}, from the stream @var{stream}.  It returns the
828 number of objects actually read, which might be less than @var{count} if
829 a read error occurs or the end of the file is reached.  This function
830 returns a value of zero (and doesn't read anything) if either @var{size}
831 or @var{count} is zero.
833 If @code{fread} encounters end of file in the middle of an object, it
834 returns the number of complete objects read, and discards the partial
835 object.  Therefore, the stream remains at the actual end of the file.
836 @end deftypefun
838 @comment stdio.h
839 @comment ISO
840 @deftypefun size_t fwrite (const void *@var{data}, size_t @var{size}, size_t @var{count}, FILE *@var{stream})
841 This function writes up to @var{count} objects of size @var{size} from
842 the array @var{data}, to the stream @var{stream}.  The return value is
843 normally @var{count}, if the call succeeds.  Any other value indicates
844 some sort of error, such as running out of space.
845 @end deftypefun
847 @node Formatted Output
848 @section Formatted Output
850 @cindex format string, for @code{printf}
851 @cindex template, for @code{printf}
852 @cindex formatted output to a stream
853 @cindex writing to a stream, formatted
854 The functions described in this section (@code{printf} and related
855 functions) provide a convenient way to perform formatted output.  You
856 call @code{printf} with a @dfn{format string} or @dfn{template string}
857 that specifies how to format the values of the remaining arguments.
859 Unless your program is a filter that specifically performs line- or
860 character-oriented processing, using @code{printf} or one of the other
861 related functions described in this section is usually the easiest and
862 most concise way to perform output.  These functions are especially
863 useful for printing error messages, tables of data, and the like.
865 @menu
866 * Formatted Output Basics::     Some examples to get you started.
867 * Output Conversion Syntax::    General syntax of conversion
868                                  specifications.
869 * Table of Output Conversions:: Summary of output conversions and
870                                  what they do.
871 * Integer Conversions::         Details about formatting of integers.
872 * Floating-Point Conversions::  Details about formatting of
873                                  floating-point numbers.
874 * Other Output Conversions::    Details about formatting of strings,
875                                  characters, pointers, and the like.
876 * Formatted Output Functions::  Descriptions of the actual functions.
877 * Dynamic Output::              Functions that allocate memory for the output.
878 * Variable Arguments Output::   @code{vprintf} and friends.
879 * Parsing a Template String::   What kinds of args does a given template
880                                  call for?
881 * Example of Parsing::          Sample program using @code{parse_printf_format}.
882 @end menu
884 @node Formatted Output Basics
885 @subsection Formatted Output Basics
887 The @code{printf} function can be used to print any number of arguments.
888 The template string argument you supply in a call provides
889 information not only about the number of additional arguments, but also
890 about their types and what style should be used for printing them.
892 Ordinary characters in the template string are simply written to the
893 output stream as-is, while @dfn{conversion specifications} introduced by
894 a @samp{%} character in the template cause subsequent arguments to be
895 formatted and written to the output stream.  For example,
896 @cindex conversion specifications (@code{printf})
898 @smallexample
899 int pct = 37;
900 char filename[] = "foo.txt";
901 printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
902         filename, pct);
903 @end smallexample
905 @noindent
906 produces output like
908 @smallexample
909 Processing of `foo.txt' is 37% finished.
910 Please be patient.
911 @end smallexample
913 This example shows the use of the @samp{%d} conversion to specify that
914 an @code{int} argument should be printed in decimal notation, the
915 @samp{%s} conversion to specify printing of a string argument, and
916 the @samp{%%} conversion to print a literal @samp{%} character.
918 There are also conversions for printing an integer argument as an
919 unsigned value in octal, decimal, or hexadecimal radix (@samp{%o},
920 @samp{%u}, or @samp{%x}, respectively); or as a character value
921 (@samp{%c}).
923 Floating-point numbers can be printed in normal, fixed-point notation
924 using the @samp{%f} conversion or in exponential notation using the
925 @samp{%e} conversion.  The @samp{%g} conversion uses either @samp{%e}
926 or @samp{%f} format, depending on what is more appropriate for the
927 magnitude of the particular number.
929 You can control formatting more precisely by writing @dfn{modifiers}
930 between the @samp{%} and the character that indicates which conversion
931 to apply.  These slightly alter the ordinary behavior of the conversion.
932 For example, most conversion specifications permit you to specify a
933 minimum field width and a flag indicating whether you want the result
934 left- or right-justified within the field.
936 The specific flags and modifiers that are permitted and their
937 interpretation vary depending on the particular conversion.  They're all
938 described in more detail in the following sections.  Don't worry if this
939 all seems excessively complicated at first; you can almost always get
940 reasonable free-format output without using any of the modifiers at all.
941 The modifiers are mostly used to make the output look ``prettier'' in
942 tables.
944 @node Output Conversion Syntax
945 @subsection Output Conversion Syntax
947 This section provides details about the precise syntax of conversion
948 specifications that can appear in a @code{printf} template
949 string.
951 Characters in the template string that are not part of a conversion
952 specification are printed as-is to the output stream.  Multibyte
953 character sequences (@pxref{Character Set Handling}) are permitted in a
954 template string.
956 The conversion specifications in a @code{printf} template string have
957 the general form:
959 @example
960 % @r{[} @var{param-no} @r{$]} @var{flags} @var{width} @r{[} . @var{precision} @r{]} @var{type} @var{conversion}
961 @end example
963 For example, in the conversion specifier @samp{%-10.8ld}, the @samp{-}
964 is a flag, @samp{10} specifies the field width, the precision is
965 @samp{8}, the letter @samp{l} is a type modifier, and @samp{d} specifies
966 the conversion style.  (This particular type specifier says to
967 print a @code{long int} argument in decimal notation, with a minimum of
968 8 digits left-justified in a field at least 10 characters wide.)
970 In more detail, output conversion specifications consist of an
971 initial @samp{%} character followed in sequence by:
973 @itemize @bullet
974 @item
975 An optional specification of the parameter used for this format.
976 Normally the parameters to the @code{printf} function are assigned to the
977 formats in the order of appearance in the format string.  But in some
978 situations (such as message translation) this is not desirable and this
979 extension allows an explicit parameter to be specified.
981 The @var{param-no} part of the format must be an integer in the range of
982 1 to the maximum number of arguments present to the function call.  Some
983 implementations limit this number to a certainly upper bound.  The exact
984 limit can be retrieved by the following constant.
986 @defvr Macro NL_ARGMAX
987 The value of @code{ARGMAX} is the maximum value allowed for the
988 specification of an positional parameter in a @code{printf} call.  The
989 actual value in effect at runtime can be retrieved by using
990 @code{sysconf} using the @code{_SC_NL_ARGMAX} parameter @pxref{Sysconf
991 Definition}.
993 Some system have a quite low limit such as @math{9} for @w{System V}
994 systems.  The GNU C library has no real limit.
995 @end defvr
997 If any of the formats has a specification for the parameter position all
998 of them in the format string shall have one.  Otherwise the behaviour is
999 undefined.
1001 @item
1002 Zero or more @dfn{flag characters} that modify the normal behavior of
1003 the conversion specification.
1004 @cindex flag character (@code{printf})
1006 @item
1007 An optional decimal integer specifying the @dfn{minimum field width}.
1008 If the normal conversion produces fewer characters than this, the field
1009 is padded with spaces to the specified width.  This is a @emph{minimum}
1010 value; if the normal conversion produces more characters than this, the
1011 field is @emph{not} truncated.  Normally, the output is right-justified
1012 within the field.
1013 @cindex minimum field width (@code{printf})
1015 You can also specify a field width of @samp{*}.  This means that the
1016 next argument in the argument list (before the actual value to be
1017 printed) is used as the field width.  The value must be an @code{int}.
1018 If the value is negative, this means to set the @samp{-} flag (see
1019 below) and to use the absolute value as the field width.
1021 @item
1022 An optional @dfn{precision} to specify the number of digits to be
1023 written for the numeric conversions.  If the precision is specified, it
1024 consists of a period (@samp{.}) followed optionally by a decimal integer
1025 (which defaults to zero if omitted).
1026 @cindex precision (@code{printf})
1028 You can also specify a precision of @samp{*}.  This means that the next
1029 argument in the argument list (before the actual value to be printed) is
1030 used as the precision.  The value must be an @code{int}, and is ignored
1031 if it is negative.  If you specify @samp{*} for both the field width and
1032 precision, the field width argument precedes the precision argument.
1033 Other C library versions may not recognize this syntax.
1035 @item
1036 An optional @dfn{type modifier character}, which is used to specify the
1037 data type of the corresponding argument if it differs from the default
1038 type.  (For example, the integer conversions assume a type of @code{int},
1039 but you can specify @samp{h}, @samp{l}, or @samp{L} for other integer
1040 types.)
1041 @cindex type modifier character (@code{printf})
1043 @item
1044 A character that specifies the conversion to be applied.
1045 @end itemize
1047 The exact options that are permitted and how they are interpreted vary
1048 between the different conversion specifiers.  See the descriptions of the
1049 individual conversions for information about the particular options that
1050 they use.
1052 With the @samp{-Wformat} option, the GNU C compiler checks calls to
1053 @code{printf} and related functions.  It examines the format string and
1054 verifies that the correct number and types of arguments are supplied.
1055 There is also a GNU C syntax to tell the compiler that a function you
1056 write uses a @code{printf}-style format string.
1057 @xref{Function Attributes, , Declaring Attributes of Functions,
1058 gcc.info, Using GNU CC}, for more information.
1060 @node Table of Output Conversions
1061 @subsection Table of Output Conversions
1062 @cindex output conversions, for @code{printf}
1064 Here is a table summarizing what all the different conversions do:
1066 @table @asis
1067 @item @samp{%d}, @samp{%i}
1068 Print an integer as a signed decimal number.  @xref{Integer
1069 Conversions}, for details.  @samp{%d} and @samp{%i} are synonymous for
1070 output, but are different when used with @code{scanf} for input
1071 (@pxref{Table of Input Conversions}).
1073 @item @samp{%o}
1074 Print an integer as an unsigned octal number.  @xref{Integer
1075 Conversions}, for details.
1077 @item @samp{%u}
1078 Print an integer as an unsigned decimal number.  @xref{Integer
1079 Conversions}, for details.
1081 @item @samp{%x}, @samp{%X}
1082 Print an integer as an unsigned hexadecimal number.  @samp{%x} uses
1083 lower-case letters and @samp{%X} uses upper-case.  @xref{Integer
1084 Conversions}, for details.
1086 @item @samp{%f}
1087 Print a floating-point number in normal (fixed-point) notation.
1088 @xref{Floating-Point Conversions}, for details.
1090 @item @samp{%e}, @samp{%E}
1091 Print a floating-point number in exponential notation.  @samp{%e} uses
1092 lower-case letters and @samp{%E} uses upper-case.  @xref{Floating-Point
1093 Conversions}, for details.
1095 @item @samp{%g}, @samp{%G}
1096 Print a floating-point number in either normal or exponential notation,
1097 whichever is more appropriate for its magnitude.  @samp{%g} uses
1098 lower-case letters and @samp{%G} uses upper-case.  @xref{Floating-Point
1099 Conversions}, for details.
1101 @item @samp{%a}, @samp{%A}
1102 Print a floating-point number in a hexadecimal fractional notation which
1103 the exponent to base 2 represented in decimal digits.  @samp{%a} uses
1104 lower-case letters and @samp{%A} uses upper-case.  @xref{Floating-Point
1105 Conversions}, for details.
1107 @item @samp{%c}
1108 Print a single character.  @xref{Other Output Conversions}.
1110 @item @samp{%s}
1111 Print a string.  @xref{Other Output Conversions}.
1113 @item @samp{%p}
1114 Print the value of a pointer.  @xref{Other Output Conversions}.
1116 @item @samp{%n}
1117 Get the number of characters printed so far.  @xref{Other Output Conversions}.
1118 Note that this conversion specification never produces any output.
1120 @item @samp{%m}
1121 Print the string corresponding to the value of @code{errno}.
1122 (This is a GNU extension.)
1123 @xref{Other Output Conversions}.
1125 @item @samp{%%}
1126 Print a literal @samp{%} character.  @xref{Other Output Conversions}.
1127 @end table
1129 If the syntax of a conversion specification is invalid, unpredictable
1130 things will happen, so don't do this.  If there aren't enough function
1131 arguments provided to supply values for all the conversion
1132 specifications in the template string, or if the arguments are not of
1133 the correct types, the results are unpredictable.  If you supply more
1134 arguments than conversion specifications, the extra argument values are
1135 simply ignored; this is sometimes useful.
1137 @node Integer Conversions
1138 @subsection Integer Conversions
1140 This section describes the options for the @samp{%d}, @samp{%i},
1141 @samp{%o}, @samp{%u}, @samp{%x}, and @samp{%X} conversion
1142 specifications.  These conversions print integers in various formats.
1144 The @samp{%d} and @samp{%i} conversion specifications both print an
1145 @code{int} argument as a signed decimal number; while @samp{%o},
1146 @samp{%u}, and @samp{%x} print the argument as an unsigned octal,
1147 decimal, or hexadecimal number (respectively).  The @samp{%X} conversion
1148 specification is just like @samp{%x} except that it uses the characters
1149 @samp{ABCDEF} as digits instead of @samp{abcdef}.
1151 The following flags are meaningful:
1153 @table @asis
1154 @item @samp{-}
1155 Left-justify the result in the field (instead of the normal
1156 right-justification).
1158 @item @samp{+}
1159 For the signed @samp{%d} and @samp{%i} conversions, print a
1160 plus sign if the value is positive.
1162 @item @samp{ }
1163 For the signed @samp{%d} and @samp{%i} conversions, if the result
1164 doesn't start with a plus or minus sign, prefix it with a space
1165 character instead.  Since the @samp{+} flag ensures that the result
1166 includes a sign, this flag is ignored if you supply both of them.
1168 @item @samp{#}
1169 For the @samp{%o} conversion, this forces the leading digit to be
1170 @samp{0}, as if by increasing the precision.  For @samp{%x} or
1171 @samp{%X}, this prefixes a leading @samp{0x} or @samp{0X} (respectively)
1172 to the result.  This doesn't do anything useful for the @samp{%d},
1173 @samp{%i}, or @samp{%u} conversions.  Using this flag produces output
1174 which can be parsed by the @code{strtoul} function (@pxref{Parsing of
1175 Integers}) and @code{scanf} with the @samp{%i} conversion
1176 (@pxref{Numeric Input Conversions}).
1178 @item @samp{'}
1179 Separate the digits into groups as specified by the locale specified for
1180 the @code{LC_NUMERIC} category; @pxref{General Numeric}.  This flag is a
1181 GNU extension.
1183 @item @samp{0}
1184 Pad the field with zeros instead of spaces.  The zeros are placed after
1185 any indication of sign or base.  This flag is ignored if the @samp{-}
1186 flag is also specified, or if a precision is specified.
1187 @end table
1189 If a precision is supplied, it specifies the minimum number of digits to
1190 appear; leading zeros are produced if necessary.  If you don't specify a
1191 precision, the number is printed with as many digits as it needs.  If
1192 you convert a value of zero with an explicit precision of zero, then no
1193 characters at all are produced.
1195 Without a type modifier, the corresponding argument is treated as an
1196 @code{int} (for the signed conversions @samp{%i} and @samp{%d}) or
1197 @code{unsigned int} (for the unsigned conversions @samp{%o}, @samp{%u},
1198 @samp{%x}, and @samp{%X}).  Recall that since @code{printf} and friends
1199 are variadic, any @code{char} and @code{short} arguments are
1200 automatically converted to @code{int} by the default argument
1201 promotions.  For arguments of other integer types, you can use these
1202 modifiers:
1204 @table @samp
1205 @item hh
1206 Specifies that the argument is a @code{signed char} or @code{unsigned
1207 char}, as appropriate.  A @code{char} argument is converted to an
1208 @code{int} or @code{unsigned int} by the default argument promotions
1209 anyway, but the @samp{h} modifier says to convert it back to a
1210 @code{char} again.
1212 This modifier was introduced in @w{ISO C99}.
1214 @item h
1215 Specifies that the argument is a @code{short int} or @code{unsigned
1216 short int}, as appropriate.  A @code{short} argument is converted to an
1217 @code{int} or @code{unsigned int} by the default argument promotions
1218 anyway, but the @samp{h} modifier says to convert it back to a
1219 @code{short} again.
1221 @item j
1222 Specifies that the argument is a @code{intmax_t} or @code{uintmax_t}, as
1223 appropriate.
1225 This modifier was introduced in @w{ISO C99}.
1227 @item l
1228 Specifies that the argument is a @code{long int} or @code{unsigned long
1229 int}, as appropriate.  Two @samp{l} characters is like the @samp{L}
1230 modifier, below.
1232 @item L
1233 @itemx ll
1234 @itemx q
1235 Specifies that the argument is a @code{long long int}.  (This type is
1236 an extension supported by the GNU C compiler.  On systems that don't
1237 support extra-long integers, this is the same as @code{long int}.)
1239 The @samp{q} modifier is another name for the same thing, which comes
1240 from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
1241 @code{int}.
1243 @item t
1244 Specifies that the argument is a @code{ptrdiff_t}.
1246 This modifier was introduced in @w{ISO C99}.
1248 @item z
1249 @itemx Z
1250 Specifies that the argument is a @code{size_t}.
1252 @samp{z} was introduced in @w{ISO C99}.  @samp{Z} is a GNU extension
1253 predating this addition and should not be used in new code.
1254 @end table
1256 Here is an example.  Using the template string:
1258 @smallexample
1259 "|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
1260 @end smallexample
1262 @noindent
1263 to print numbers using the different options for the @samp{%d}
1264 conversion gives results like:
1266 @smallexample
1267 |    0|0    |   +0|+0   |    0|00000|     |   00|0|
1268 |    1|1    |   +1|+1   |    1|00001|    1|   01|1|
1269 |   -1|-1   |   -1|-1   |   -1|-0001|   -1|  -01|-1|
1270 |100000|100000|+100000| 100000|100000|100000|100000|100000|
1271 @end smallexample
1273 In particular, notice what happens in the last case where the number
1274 is too large to fit in the minimum field width specified.
1276 Here are some more examples showing how unsigned integers print under
1277 various format options, using the template string:
1279 @smallexample
1280 "|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"
1281 @end smallexample
1283 @smallexample
1284 |    0|    0|    0|    0|    0|  0x0|  0X0|0x00000000|
1285 |    1|    1|    1|    1|   01|  0x1|  0X1|0x00000001|
1286 |100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|
1287 @end smallexample
1290 @node Floating-Point Conversions
1291 @subsection Floating-Point Conversions
1293 This section discusses the conversion specifications for floating-point
1294 numbers: the @samp{%f}, @samp{%e}, @samp{%E}, @samp{%g}, and @samp{%G}
1295 conversions.
1297 The @samp{%f} conversion prints its argument in fixed-point notation,
1298 producing output of the form
1299 @w{[@code{-}]@var{ddd}@code{.}@var{ddd}},
1300 where the number of digits following the decimal point is controlled
1301 by the precision you specify.
1303 The @samp{%e} conversion prints its argument in exponential notation,
1304 producing output of the form
1305 @w{[@code{-}]@var{d}@code{.}@var{ddd}@code{e}[@code{+}|@code{-}]@var{dd}}.
1306 Again, the number of digits following the decimal point is controlled by
1307 the precision.  The exponent always contains at least two digits.  The
1308 @samp{%E} conversion is similar but the exponent is marked with the letter
1309 @samp{E} instead of @samp{e}.
1311 The @samp{%g} and @samp{%G} conversions print the argument in the style
1312 of @samp{%e} or @samp{%E} (respectively) if the exponent would be less
1313 than -4 or greater than or equal to the precision; otherwise they use the
1314 @samp{%f} style.  Trailing zeros are removed from the fractional portion
1315 of the result and a decimal-point character appears only if it is
1316 followed by a digit.
1318 The @samp{%a} and @samp{%A} conversions are meant for representing
1319 floating-point numbers exactly in textual form so that they can be
1320 exchanged as texts between different programs and/or machines.  The
1321 numbers are represented is the form
1322 @w{[@code{-}]@code{0x}@var{h}@code{.}@var{hhh}@code{p}[@code{+}|@code{-}]@var{dd}}.
1323 At the left of the decimal-point character exactly one digit is print.
1324 This character is only @code{0} if the number is denormalized.
1325 Otherwise the value is unspecified; it is implementation dependent how many
1326 bits are used.  The number of hexadecimal digits on the right side of
1327 the decimal-point character is equal to the precision.  If the precision
1328 is zero it is determined to be large enough to provide an exact
1329 representation of the number (or it is large enough to distinguish two
1330 adjacent values if the @code{FLT_RADIX} is not a power of 2,
1331 @pxref{Floating Point Parameters}).  For the @samp{%a} conversion
1332 lower-case characters are used to represent the hexadecimal number and
1333 the prefix and exponent sign are printed as @code{0x} and @code{p}
1334 respectively.  Otherwise upper-case characters are used and @code{0X}
1335 and @code{P} are used for the representation of prefix and exponent
1336 string.  The exponent to the base of two is printed as a decimal number
1337 using at least one digit but at most as many digits as necessary to
1338 represent the value exactly.
1340 If the value to be printed represents infinity or a NaN, the output is
1341 @w{[@code{-}]@code{inf}} or @code{nan} respectively if the conversion
1342 specifier is @samp{%a}, @samp{%e}, @samp{%f}, or @samp{%g} and it is
1343 @w{[@code{-}]@code{INF}} or @code{NAN} respectively if the conversion is
1344 @samp{%A}, @samp{%E}, or @samp{%G}.
1346 The following flags can be used to modify the behavior:
1348 @comment We use @asis instead of @samp so we can have ` ' as an item.
1349 @table @asis
1350 @item @samp{-}
1351 Left-justify the result in the field.  Normally the result is
1352 right-justified.
1354 @item @samp{+}
1355 Always include a plus or minus sign in the result.
1357 @item @samp{ }
1358 If the result doesn't start with a plus or minus sign, prefix it with a
1359 space instead.  Since the @samp{+} flag ensures that the result includes
1360 a sign, this flag is ignored if you supply both of them.
1362 @item @samp{#}
1363 Specifies that the result should always include a decimal point, even
1364 if no digits follow it.  For the @samp{%g} and @samp{%G} conversions,
1365 this also forces trailing zeros after the decimal point to be left
1366 in place where they would otherwise be removed.
1368 @item @samp{'}
1369 Separate the digits of the integer part of the result into groups as
1370 specified by the locale specified for the @code{LC_NUMERIC} category;
1371 @pxref{General Numeric}.  This flag is a GNU extension.
1373 @item @samp{0}
1374 Pad the field with zeros instead of spaces; the zeros are placed
1375 after any sign.  This flag is ignored if the @samp{-} flag is also
1376 specified.
1377 @end table
1379 The precision specifies how many digits follow the decimal-point
1380 character for the @samp{%f}, @samp{%e}, and @samp{%E} conversions.  For
1381 these conversions, the default precision is @code{6}.  If the precision
1382 is explicitly @code{0}, this suppresses the decimal point character
1383 entirely.  For the @samp{%g} and @samp{%G} conversions, the precision
1384 specifies how many significant digits to print.  Significant digits are
1385 the first digit before the decimal point, and all the digits after it.
1386 If the precision is @code{0} or not specified for @samp{%g} or @samp{%G},
1387 it is treated like a value of @code{1}.  If the value being printed
1388 cannot be expressed accurately in the specified number of digits, the
1389 value is rounded to the nearest number that fits.
1391 Without a type modifier, the floating-point conversions use an argument
1392 of type @code{double}.  (By the default argument promotions, any
1393 @code{float} arguments are automatically converted to @code{double}.)
1394 The following type modifier is supported:
1396 @table @samp
1397 @item L
1398 An uppercase @samp{L} specifies that the argument is a @code{long
1399 double}.
1400 @end table
1402 Here are some examples showing how numbers print using the various
1403 floating-point conversions.  All of the numbers were printed using
1404 this template string:
1406 @smallexample
1407 "|%13.4a|%13.4f|%13.4e|%13.4g|\n"
1408 @end smallexample
1410 Here is the output:
1412 @smallexample
1413 |  0x0.0000p+0|       0.0000|   0.0000e+00|            0|
1414 |  0x1.0000p-1|       0.5000|   5.0000e-01|          0.5|
1415 |  0x1.0000p+0|       1.0000|   1.0000e+00|            1|
1416 | -0x1.0000p+0|      -1.0000|  -1.0000e+00|           -1|
1417 |  0x1.9000p+6|     100.0000|   1.0000e+02|          100|
1418 |  0x1.f400p+9|    1000.0000|   1.0000e+03|         1000|
1419 | 0x1.3880p+13|   10000.0000|   1.0000e+04|        1e+04|
1420 | 0x1.81c8p+13|   12345.0000|   1.2345e+04|    1.234e+04|
1421 | 0x1.86a0p+16|  100000.0000|   1.0000e+05|        1e+05|
1422 | 0x1.e240p+16|  123456.0000|   1.2346e+05|    1.235e+05|
1423 @end smallexample
1425 Notice how the @samp{%g} conversion drops trailing zeros.
1427 @node Other Output Conversions
1428 @subsection Other Output Conversions
1430 This section describes miscellaneous conversions for @code{printf}.
1432 The @samp{%c} conversion prints a single character.  The @code{int}
1433 argument is first converted to an @code{unsigned char}.  The @samp{-}
1434 flag can be used to specify left-justification in the field, but no
1435 other flags are defined, and no precision or type modifier can be given.
1436 For example:
1438 @smallexample
1439 printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');
1440 @end smallexample
1442 @noindent
1443 prints @samp{hello}.
1445 The @samp{%s} conversion prints a string.  The corresponding argument
1446 must be of type @code{char *} (or @code{const char *}).  A precision can
1447 be specified to indicate the maximum number of characters to write;
1448 otherwise characters in the string up to but not including the
1449 terminating null character are written to the output stream.  The
1450 @samp{-} flag can be used to specify left-justification in the field,
1451 but no other flags or type modifiers are defined for this conversion.
1452 For example:
1454 @smallexample
1455 printf ("%3s%-6s", "no", "where");
1456 @end smallexample
1458 @noindent
1459 prints @samp{ nowhere }.
1461 If you accidentally pass a null pointer as the argument for a @samp{%s}
1462 conversion, the GNU library prints it as @samp{(null)}.  We think this
1463 is more useful than crashing.  But it's not good practice to pass a null
1464 argument intentionally.
1466 The @samp{%m} conversion prints the string corresponding to the error
1467 code in @code{errno}.  @xref{Error Messages}.  Thus:
1469 @smallexample
1470 fprintf (stderr, "can't open `%s': %m\n", filename);
1471 @end smallexample
1473 @noindent
1474 is equivalent to:
1476 @smallexample
1477 fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
1478 @end smallexample
1480 @noindent
1481 The @samp{%m} conversion is a GNU C library extension.
1483 The @samp{%p} conversion prints a pointer value.  The corresponding
1484 argument must be of type @code{void *}.  In practice, you can use any
1485 type of pointer.
1487 In the GNU system, non-null pointers are printed as unsigned integers,
1488 as if a @samp{%#x} conversion were used.  Null pointers print as
1489 @samp{(nil)}.  (Pointers might print differently in other systems.)
1491 For example:
1493 @smallexample
1494 printf ("%p", "testing");
1495 @end smallexample
1497 @noindent
1498 prints @samp{0x} followed by a hexadecimal number---the address of the
1499 string constant @code{"testing"}.  It does not print the word
1500 @samp{testing}.
1502 You can supply the @samp{-} flag with the @samp{%p} conversion to
1503 specify left-justification, but no other flags, precision, or type
1504 modifiers are defined.
1506 The @samp{%n} conversion is unlike any of the other output conversions.
1507 It uses an argument which must be a pointer to an @code{int}, but
1508 instead of printing anything it stores the number of characters printed
1509 so far by this call at that location.  The @samp{h} and @samp{l} type
1510 modifiers are permitted to specify that the argument is of type
1511 @code{short int *} or @code{long int *} instead of @code{int *}, but no
1512 flags, field width, or precision are permitted.
1514 For example,
1516 @smallexample
1517 int nchar;
1518 printf ("%d %s%n\n", 3, "bears", &nchar);
1519 @end smallexample
1521 @noindent
1522 prints:
1524 @smallexample
1525 3 bears
1526 @end smallexample
1528 @noindent
1529 and sets @code{nchar} to @code{7}, because @samp{3 bears} is seven
1530 characters.
1533 The @samp{%%} conversion prints a literal @samp{%} character.  This
1534 conversion doesn't use an argument, and no flags, field width,
1535 precision, or type modifiers are permitted.
1538 @node Formatted Output Functions
1539 @subsection Formatted Output Functions
1541 This section describes how to call @code{printf} and related functions.
1542 Prototypes for these functions are in the header file @file{stdio.h}.
1543 Because these functions take a variable number of arguments, you
1544 @emph{must} declare prototypes for them before using them.  Of course,
1545 the easiest way to make sure you have all the right prototypes is to
1546 just include @file{stdio.h}.
1547 @pindex stdio.h
1549 @comment stdio.h
1550 @comment ISO
1551 @deftypefun int printf (const char *@var{template}, @dots{})
1552 The @code{printf} function prints the optional arguments under the
1553 control of the template string @var{template} to the stream
1554 @code{stdout}.  It returns the number of characters printed, or a
1555 negative value if there was an output error.
1556 @end deftypefun
1558 @comment stdio.h
1559 @comment ISO
1560 @deftypefun int fprintf (FILE *@var{stream}, const char *@var{template}, @dots{})
1561 This function is just like @code{printf}, except that the output is
1562 written to the stream @var{stream} instead of @code{stdout}.
1563 @end deftypefun
1565 @comment stdio.h
1566 @comment ISO
1567 @deftypefun int sprintf (char *@var{s}, const char *@var{template}, @dots{})
1568 This is like @code{printf}, except that the output is stored in the character
1569 array @var{s} instead of written to a stream.  A null character is written
1570 to mark the end of the string.
1572 The @code{sprintf} function returns the number of characters stored in
1573 the array @var{s}, not including the terminating null character.
1575 The behavior of this function is undefined if copying takes place
1576 between objects that overlap---for example, if @var{s} is also given
1577 as an argument to be printed under control of the @samp{%s} conversion.
1578 @xref{Copying and Concatenation}.
1580 @strong{Warning:} The @code{sprintf} function can be @strong{dangerous}
1581 because it can potentially output more characters than can fit in the
1582 allocation size of the string @var{s}.  Remember that the field width
1583 given in a conversion specification is only a @emph{minimum} value.
1585 To avoid this problem, you can use @code{snprintf} or @code{asprintf},
1586 described below.
1587 @end deftypefun
1589 @comment stdio.h
1590 @comment GNU
1591 @deftypefun int snprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, @dots{})
1592 The @code{snprintf} function is similar to @code{sprintf}, except that
1593 the @var{size} argument specifies the maximum number of characters to
1594 produce.  The trailing null character is counted towards this limit, so
1595 you should allocate at least @var{size} characters for the string @var{s}.
1597 The return value is the number of characters which would be generated
1598 for the given input, excluding the trailing null.  If this value is
1599 greater or equal to @var{size}, not all characters from the result have
1600 been stored in @var{s}.  You should try again with a bigger output
1601 string.  Here is an example of doing this:
1603 @smallexample
1604 @group
1605 /* @r{Construct a message describing the value of a variable}
1606    @r{whose name is @var{name} and whose value is @var{value}.} */
1607 char *
1608 make_message (char *name, char *value)
1610   /* @r{Guess we need no more than 100 chars of space.} */
1611   int size = 100;
1612   char *buffer = (char *) xmalloc (size);
1613   int nchars;
1614 @end group
1615 @group
1616   if (buffer == NULL)
1617     return NULL;
1619  /* @r{Try to print in the allocated space.} */
1620   nchars = snprintf (buffer, size, "value of %s is %s",
1621                      name, value);
1622 @end group
1623 @group
1624   if (nchars >= size)
1625     @{
1626       /* @r{Reallocate buffer now that we know
1627          how much space is needed.} */
1628       buffer = (char *) xrealloc (buffer, nchars + 1);
1630       if (buffer != NULL)
1631         /* @r{Try again.} */
1632         snprintf (buffer, size, "value of %s is %s",
1633                   name, value);
1634     @}
1635   /* @r{The last call worked, return the string.} */
1636   return buffer;
1638 @end group
1639 @end smallexample
1641 In practice, it is often easier just to use @code{asprintf}, below.
1643 @strong{Attention:} In the GNU C library version 2.0 the return value
1644 is the number of characters stored, not including the terminating null.
1645 If this value equals @code{@var{size} - 1}, then there was not enough
1646 space in @var{s} for all the output.  This change was necessary with
1647 the adoption of snprintf by ISO C99.
1648 @end deftypefun
1650 @node Dynamic Output
1651 @subsection Dynamically Allocating Formatted Output
1653 The functions in this section do formatted output and place the results
1654 in dynamically allocated memory.
1656 @comment stdio.h
1657 @comment GNU
1658 @deftypefun int asprintf (char **@var{ptr}, const char *@var{template}, @dots{})
1659 This function is similar to @code{sprintf}, except that it dynamically
1660 allocates a string (as with @code{malloc}; @pxref{Unconstrained
1661 Allocation}) to hold the output, instead of putting the output in a
1662 buffer you allocate in advance.  The @var{ptr} argument should be the
1663 address of a @code{char *} object, and @code{asprintf} stores a pointer
1664 to the newly allocated string at that location.
1666 The return value is the number of characters allocated for the buffer, or
1667 less than zero if an error occured. Usually this means that the buffer
1668 could not be allocated.
1670 Here is how to use @code{asprintf} to get the same result as the
1671 @code{snprintf} example, but more easily:
1673 @smallexample
1674 /* @r{Construct a message describing the value of a variable}
1675    @r{whose name is @var{name} and whose value is @var{value}.} */
1676 char *
1677 make_message (char *name, char *value)
1679   char *result;
1680   if (asprintf (&result, "value of %s is %s", name, value) < 0)
1681     return NULL;
1682   return result;
1684 @end smallexample
1685 @end deftypefun
1687 @comment stdio.h
1688 @comment GNU
1689 @deftypefun int obstack_printf (struct obstack *@var{obstack}, const char *@var{template}, @dots{})
1690 This function is similar to @code{asprintf}, except that it uses the
1691 obstack @var{obstack} to allocate the space.  @xref{Obstacks}.
1693 The characters are written onto the end of the current object.
1694 To get at them, you must finish the object with @code{obstack_finish}
1695 (@pxref{Growing Objects}).@refill
1696 @end deftypefun
1698 @node Variable Arguments Output
1699 @subsection Variable Arguments Output Functions
1701 The functions @code{vprintf} and friends are provided so that you can
1702 define your own variadic @code{printf}-like functions that make use of
1703 the same internals as the built-in formatted output functions.
1705 The most natural way to define such functions would be to use a language
1706 construct to say, ``Call @code{printf} and pass this template plus all
1707 of my arguments after the first five.''  But there is no way to do this
1708 in C, and it would be hard to provide a way, since at the C language
1709 level there is no way to tell how many arguments your function received.
1711 Since that method is impossible, we provide alternative functions, the
1712 @code{vprintf} series, which lets you pass a @code{va_list} to describe
1713 ``all of my arguments after the first five.''
1715 When it is sufficient to define a macro rather than a real function,
1716 the GNU C compiler provides a way to do this much more easily with macros.
1717 For example:
1719 @smallexample
1720 #define myprintf(a, b, c, d, e, rest...) \
1721             printf (mytemplate , ## rest...)
1722 @end smallexample
1724 @noindent
1725 @xref{Macro Varargs, , Macros with Variable Numbers of Arguments,
1726 gcc.info, Using GNU CC}, for details.  But this is limited to macros,
1727 and does not apply to real functions at all.
1729 Before calling @code{vprintf} or the other functions listed in this
1730 section, you @emph{must} call @code{va_start} (@pxref{Variadic
1731 Functions}) to initialize a pointer to the variable arguments.  Then you
1732 can call @code{va_arg} to fetch the arguments that you want to handle
1733 yourself.  This advances the pointer past those arguments.
1735 Once your @code{va_list} pointer is pointing at the argument of your
1736 choice, you are ready to call @code{vprintf}.  That argument and all
1737 subsequent arguments that were passed to your function are used by
1738 @code{vprintf} along with the template that you specified separately.
1740 In some other systems, the @code{va_list} pointer may become invalid
1741 after the call to @code{vprintf}, so you must not use @code{va_arg}
1742 after you call @code{vprintf}.  Instead, you should call @code{va_end}
1743 to retire the pointer from service.  However, you can safely call
1744 @code{va_start} on another pointer variable and begin fetching the
1745 arguments again through that pointer.  Calling @code{vprintf} does not
1746 destroy the argument list of your function, merely the particular
1747 pointer that you passed to it.
1749 GNU C does not have such restrictions.  You can safely continue to fetch
1750 arguments from a @code{va_list} pointer after passing it to
1751 @code{vprintf}, and @code{va_end} is a no-op.  (Note, however, that
1752 subsequent @code{va_arg} calls will fetch the same arguments which
1753 @code{vprintf} previously used.)
1755 Prototypes for these functions are declared in @file{stdio.h}.
1756 @pindex stdio.h
1758 @comment stdio.h
1759 @comment ISO
1760 @deftypefun int vprintf (const char *@var{template}, va_list @var{ap})
1761 This function is similar to @code{printf} except that, instead of taking
1762 a variable number of arguments directly, it takes an argument list
1763 pointer @var{ap}.
1764 @end deftypefun
1766 @comment stdio.h
1767 @comment ISO
1768 @deftypefun int vfprintf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
1769 This is the equivalent of @code{fprintf} with the variable argument list
1770 specified directly as for @code{vprintf}.
1771 @end deftypefun
1773 @comment stdio.h
1774 @comment ISO
1775 @deftypefun int vsprintf (char *@var{s}, const char *@var{template}, va_list @var{ap})
1776 This is the equivalent of @code{sprintf} with the variable argument list
1777 specified directly as for @code{vprintf}.
1778 @end deftypefun
1780 @comment stdio.h
1781 @comment GNU
1782 @deftypefun int vsnprintf (char *@var{s}, size_t @var{size}, const char *@var{template}, va_list @var{ap})
1783 This is the equivalent of @code{snprintf} with the variable argument list
1784 specified directly as for @code{vprintf}.
1785 @end deftypefun
1787 @comment stdio.h
1788 @comment GNU
1789 @deftypefun int vasprintf (char **@var{ptr}, const char *@var{template}, va_list @var{ap})
1790 The @code{vasprintf} function is the equivalent of @code{asprintf} with the
1791 variable argument list specified directly as for @code{vprintf}.
1792 @end deftypefun
1794 @comment stdio.h
1795 @comment GNU
1796 @deftypefun int obstack_vprintf (struct obstack *@var{obstack}, const char *@var{template}, va_list @var{ap})
1797 The @code{obstack_vprintf} function is the equivalent of
1798 @code{obstack_printf} with the variable argument list specified directly
1799 as for @code{vprintf}.@refill
1800 @end deftypefun
1802 Here's an example showing how you might use @code{vfprintf}.  This is a
1803 function that prints error messages to the stream @code{stderr}, along
1804 with a prefix indicating the name of the program
1805 (@pxref{Error Messages}, for a description of
1806 @code{program_invocation_short_name}).
1808 @smallexample
1809 @group
1810 #include <stdio.h>
1811 #include <stdarg.h>
1813 void
1814 eprintf (const char *template, ...)
1816   va_list ap;
1817   extern char *program_invocation_short_name;
1819   fprintf (stderr, "%s: ", program_invocation_short_name);
1820   va_start (ap, template);
1821   vfprintf (stderr, template, ap);
1822   va_end (ap);
1824 @end group
1825 @end smallexample
1827 @noindent
1828 You could call @code{eprintf} like this:
1830 @smallexample
1831 eprintf ("file `%s' does not exist\n", filename);
1832 @end smallexample
1834 In GNU C, there is a special construct you can use to let the compiler
1835 know that a function uses a @code{printf}-style format string.  Then it
1836 can check the number and types of arguments in each call to the
1837 function, and warn you when they do not match the format string.
1838 For example, take this declaration of @code{eprintf}:
1840 @smallexample
1841 void eprintf (const char *template, ...)
1842         __attribute__ ((format (printf, 1, 2)));
1843 @end smallexample
1845 @noindent
1846 This tells the compiler that @code{eprintf} uses a format string like
1847 @code{printf} (as opposed to @code{scanf}; @pxref{Formatted Input});
1848 the format string appears as the first argument;
1849 and the arguments to satisfy the format begin with the second.
1850 @xref{Function Attributes, , Declaring Attributes of Functions,
1851 gcc.info, Using GNU CC}, for more information.
1853 @node Parsing a Template String
1854 @subsection Parsing a Template String
1855 @cindex parsing a template string
1857 You can use the function @code{parse_printf_format} to obtain
1858 information about the number and types of arguments that are expected by
1859 a given template string.  This function permits interpreters that
1860 provide interfaces to @code{printf} to avoid passing along invalid
1861 arguments from the user's program, which could cause a crash.
1863 All the symbols described in this section are declared in the header
1864 file @file{printf.h}.
1866 @comment printf.h
1867 @comment GNU
1868 @deftypefun size_t parse_printf_format (const char *@var{template}, size_t @var{n}, int *@var{argtypes})
1869 This function returns information about the number and types of
1870 arguments expected by the @code{printf} template string @var{template}.
1871 The information is stored in the array @var{argtypes}; each element of
1872 this array describes one argument.  This information is encoded using
1873 the various @samp{PA_} macros, listed below.
1875 The argument @var{n} specifies the number of elements in the array
1876 @var{argtypes}.  This is the maximum number of elements that
1877 @code{parse_printf_format} will try to write.
1879 @code{parse_printf_format} returns the total number of arguments required
1880 by @var{template}.  If this number is greater than @var{n}, then the
1881 information returned describes only the first @var{n} arguments.  If you
1882 want information about additional arguments, allocate a bigger
1883 array and call @code{parse_printf_format} again.
1884 @end deftypefun
1886 The argument types are encoded as a combination of a basic type and
1887 modifier flag bits.
1889 @comment printf.h
1890 @comment GNU
1891 @deftypevr Macro int PA_FLAG_MASK
1892 This macro is a bitmask for the type modifier flag bits.  You can write
1893 the expression @code{(argtypes[i] & PA_FLAG_MASK)} to extract just the
1894 flag bits for an argument, or @code{(argtypes[i] & ~PA_FLAG_MASK)} to
1895 extract just the basic type code.
1896 @end deftypevr
1898 Here are symbolic constants that represent the basic types; they stand
1899 for integer values.
1901 @vtable @code
1902 @comment printf.h
1903 @comment GNU
1904 @item PA_INT
1905 This specifies that the base type is @code{int}.
1907 @comment printf.h
1908 @comment GNU
1909 @item PA_CHAR
1910 This specifies that the base type is @code{int}, cast to @code{char}.
1912 @comment printf.h
1913 @comment GNU
1914 @item PA_STRING
1915 This specifies that the base type is @code{char *}, a null-terminated string.
1917 @comment printf.h
1918 @comment GNU
1919 @item PA_POINTER
1920 This specifies that the base type is @code{void *}, an arbitrary pointer.
1922 @comment printf.h
1923 @comment GNU
1924 @item PA_FLOAT
1925 This specifies that the base type is @code{float}.
1927 @comment printf.h
1928 @comment GNU
1929 @item PA_DOUBLE
1930 This specifies that the base type is @code{double}.
1932 @comment printf.h
1933 @comment GNU
1934 @item PA_LAST
1935 You can define additional base types for your own programs as offsets
1936 from @code{PA_LAST}.  For example, if you have data types @samp{foo}
1937 and @samp{bar} with their own specialized @code{printf} conversions,
1938 you could define encodings for these types as:
1940 @smallexample
1941 #define PA_FOO  PA_LAST
1942 #define PA_BAR  (PA_LAST + 1)
1943 @end smallexample
1944 @end vtable
1946 Here are the flag bits that modify a basic type.  They are combined with
1947 the code for the basic type using inclusive-or.
1949 @vtable @code
1950 @comment printf.h
1951 @comment GNU
1952 @item PA_FLAG_PTR
1953 If this bit is set, it indicates that the encoded type is a pointer to
1954 the base type, rather than an immediate value.
1955 For example, @samp{PA_INT|PA_FLAG_PTR} represents the type @samp{int *}.
1957 @comment printf.h
1958 @comment GNU
1959 @item PA_FLAG_SHORT
1960 If this bit is set, it indicates that the base type is modified with
1961 @code{short}.  (This corresponds to the @samp{h} type modifier.)
1963 @comment printf.h
1964 @comment GNU
1965 @item PA_FLAG_LONG
1966 If this bit is set, it indicates that the base type is modified with
1967 @code{long}.  (This corresponds to the @samp{l} type modifier.)
1969 @comment printf.h
1970 @comment GNU
1971 @item PA_FLAG_LONG_LONG
1972 If this bit is set, it indicates that the base type is modified with
1973 @code{long long}.  (This corresponds to the @samp{L} type modifier.)
1975 @comment printf.h
1976 @comment GNU
1977 @item PA_FLAG_LONG_DOUBLE
1978 This is a synonym for @code{PA_FLAG_LONG_LONG}, used by convention with
1979 a base type of @code{PA_DOUBLE} to indicate a type of @code{long double}.
1980 @end vtable
1982 @ifinfo
1983 For an example of using these facilities, see @ref{Example of Parsing}.
1984 @end ifinfo
1986 @node Example of Parsing
1987 @subsection Example of Parsing a Template String
1989 Here is an example of decoding argument types for a format string.  We
1990 assume this is part of an interpreter which contains arguments of type
1991 @code{NUMBER}, @code{CHAR}, @code{STRING} and @code{STRUCTURE} (and
1992 perhaps others which are not valid here).
1994 @smallexample
1995 /* @r{Test whether the @var{nargs} specified objects}
1996    @r{in the vector @var{args} are valid}
1997    @r{for the format string @var{format}:}
1998    @r{if so, return 1.}
1999    @r{If not, return 0 after printing an error message.}  */
2002 validate_args (char *format, int nargs, OBJECT *args)
2004   int *argtypes;
2005   int nwanted;
2007   /* @r{Get the information about the arguments.}
2008      @r{Each conversion specification must be at least two characters}
2009      @r{long, so there cannot be more specifications than half the}
2010      @r{length of the string.}  */
2012   argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
2013   nwanted = parse_printf_format (string, nelts, argtypes);
2015   /* @r{Check the number of arguments.}  */
2016   if (nwanted > nargs)
2017     @{
2018       error ("too few arguments (at least %d required)", nwanted);
2019       return 0;
2020     @}
2022   /* @r{Check the C type wanted for each argument}
2023      @r{and see if the object given is suitable.}  */
2024   for (i = 0; i < nwanted; i++)
2025     @{
2026       int wanted;
2028       if (argtypes[i] & PA_FLAG_PTR)
2029         wanted = STRUCTURE;
2030       else
2031         switch (argtypes[i] & ~PA_FLAG_MASK)
2032           @{
2033           case PA_INT:
2034           case PA_FLOAT:
2035           case PA_DOUBLE:
2036             wanted = NUMBER;
2037             break;
2038           case PA_CHAR:
2039             wanted = CHAR;
2040             break;
2041           case PA_STRING:
2042             wanted = STRING;
2043             break;
2044           case PA_POINTER:
2045             wanted = STRUCTURE;
2046             break;
2047           @}
2048       if (TYPE (args[i]) != wanted)
2049         @{
2050           error ("type mismatch for arg number %d", i);
2051           return 0;
2052         @}
2053     @}
2054   return 1;
2056 @end smallexample
2058 @node Customizing Printf
2059 @section Customizing @code{printf}
2060 @cindex customizing @code{printf}
2061 @cindex defining new @code{printf} conversions
2062 @cindex extending @code{printf}
2064 The GNU C library lets you define your own custom conversion specifiers
2065 for @code{printf} template strings, to teach @code{printf} clever ways
2066 to print the important data structures of your program.
2068 The way you do this is by registering the conversion with the function
2069 @code{register_printf_function}; see @ref{Registering New Conversions}.
2070 One of the arguments you pass to this function is a pointer to a handler
2071 function that produces the actual output; see @ref{Defining the Output
2072 Handler}, for information on how to write this function.
2074 You can also install a function that just returns information about the
2075 number and type of arguments expected by the conversion specifier.
2076 @xref{Parsing a Template String}, for information about this.
2078 The facilities of this section are declared in the header file
2079 @file{printf.h}.
2081 @menu
2082 * Registering New Conversions::         Using @code{register_printf_function}
2083                                          to register a new output conversion.
2084 * Conversion Specifier Options::        The handler must be able to get
2085                                          the options specified in the
2086                                          template when it is called.
2087 * Defining the Output Handler::         Defining the handler and arginfo
2088                                          functions that are passed as arguments
2089                                          to @code{register_printf_function}.
2090 * Printf Extension Example::            How to define a @code{printf}
2091                                          handler function.
2092 * Predefined Printf Handlers::          Predefined @code{printf} handlers.
2093 @end menu
2095 @strong{Portability Note:} The ability to extend the syntax of
2096 @code{printf} template strings is a GNU extension.  ISO standard C has
2097 nothing similar.
2099 @node Registering New Conversions
2100 @subsection Registering New Conversions
2102 The function to register a new output conversion is
2103 @code{register_printf_function}, declared in @file{printf.h}.
2104 @pindex printf.h
2106 @comment printf.h
2107 @comment GNU
2108 @deftypefun int register_printf_function (int @var{spec}, printf_function @var{handler-function}, printf_arginfo_function @var{arginfo-function})
2109 This function defines the conversion specifier character @var{spec}.
2110 Thus, if @var{spec} is @code{'Y'}, it defines the conversion @samp{%Y}.
2111 You can redefine the built-in conversions like @samp{%s}, but flag
2112 characters like @samp{#} and type modifiers like @samp{l} can never be
2113 used as conversions; calling @code{register_printf_function} for those
2114 characters has no effect.  It is advisable not to use lowercase letters,
2115 since the ISO C standard warns that additional lowercase letters may be
2116 standardized in future editions of the standard.
2118 The @var{handler-function} is the function called by @code{printf} and
2119 friends when this conversion appears in a template string.
2120 @xref{Defining the Output Handler}, for information about how to define
2121 a function to pass as this argument.  If you specify a null pointer, any
2122 existing handler function for @var{spec} is removed.
2124 The @var{arginfo-function} is the function called by
2125 @code{parse_printf_format} when this conversion appears in a
2126 template string.  @xref{Parsing a Template String}, for information
2127 about this.
2129 @c The following is not true anymore.  The `parse_printf_format' function
2130 @c is now also called from `vfprintf' via `parse_one_spec'.
2131 @c --drepper@gnu, 1996/11/14
2133 @c Normally, you install both functions for a conversion at the same time,
2134 @c but if you are never going to call @code{parse_printf_format}, you do
2135 @c not need to define an arginfo function.
2137 @strong{Attention:} In the GNU C library versions before 2.0 the
2138 @var{arginfo-function} function did not need to be installed unless
2139 the user used the @code{parse_printf_format} function.  This has changed.
2140 Now a call to any of the @code{printf} functions will call this
2141 function when this format specifier appears in the format string.
2143 The return value is @code{0} on success, and @code{-1} on failure
2144 (which occurs if @var{spec} is out of range).
2146 You can redefine the standard output conversions, but this is probably
2147 not a good idea because of the potential for confusion.  Library routines
2148 written by other people could break if you do this.
2149 @end deftypefun
2151 @node Conversion Specifier Options
2152 @subsection Conversion Specifier Options
2154 If you define a meaning for @samp{%A}, what if the template contains
2155 @samp{%+23A} or @samp{%-#A}?  To implement a sensible meaning for these,
2156 the handler when called needs to be able to get the options specified in
2157 the template.
2159 Both the @var{handler-function} and @var{arginfo-function} accept an
2160 argument that points to a @code{struct printf_info}, which contains
2161 information about the options appearing in an instance of the conversion
2162 specifier.  This data type is declared in the header file
2163 @file{printf.h}.
2164 @pindex printf.h
2166 @comment printf.h
2167 @comment GNU
2168 @deftp {Type} {struct printf_info}
2169 This structure is used to pass information about the options appearing
2170 in an instance of a conversion specifier in a @code{printf} template
2171 string to the handler and arginfo functions for that specifier.  It
2172 contains the following members:
2174 @table @code
2175 @item int prec
2176 This is the precision specified.  The value is @code{-1} if no precision
2177 was specified.  If the precision was given as @samp{*}, the
2178 @code{printf_info} structure passed to the handler function contains the
2179 actual value retrieved from the argument list.  But the structure passed
2180 to the arginfo function contains a value of @code{INT_MIN}, since the
2181 actual value is not known.
2183 @item int width
2184 This is the minimum field width specified.  The value is @code{0} if no
2185 width was specified.  If the field width was given as @samp{*}, the
2186 @code{printf_info} structure passed to the handler function contains the
2187 actual value retrieved from the argument list.  But the structure passed
2188 to the arginfo function contains a value of @code{INT_MIN}, since the
2189 actual value is not known.
2191 @item wchar_t spec
2192 This is the conversion specifier character specified.  It's stored in
2193 the structure so that you can register the same handler function for
2194 multiple characters, but still have a way to tell them apart when the
2195 handler function is called.
2197 @item unsigned int is_long_double
2198 This is a boolean that is true if the @samp{L}, @samp{ll}, or @samp{q}
2199 type modifier was specified.  For integer conversions, this indicates
2200 @code{long long int}, as opposed to @code{long double} for floating
2201 point conversions.
2203 @item unsigned int is_char
2204 This is a boolean that is true if the @samp{hh} type modifier was specified.
2206 @item unsigned int is_short
2207 This is a boolean that is true if the @samp{h} type modifier was specified.
2209 @item unsigned int is_long
2210 This is a boolean that is true if the @samp{l} type modifier was specified.
2212 @item unsigned int alt
2213 This is a boolean that is true if the @samp{#} flag was specified.
2215 @item unsigned int space
2216 This is a boolean that is true if the @samp{ } flag was specified.
2218 @item unsigned int left
2219 This is a boolean that is true if the @samp{-} flag was specified.
2221 @item unsigned int showsign
2222 This is a boolean that is true if the @samp{+} flag was specified.
2224 @item unsigned int group
2225 This is a boolean that is true if the @samp{'} flag was specified.
2227 @item unsigned int extra
2228 This flag has a special meaning depending on the context.  It could
2229 be used freely by the user-defined handlers but when called from
2230 the @code{printf} function this variable always contains the value
2231 @code{0}.
2233 @item unsigned int wide
2234 This flag is set if the stream is wide oriented.
2236 @item wchar_t pad
2237 This is the character to use for padding the output to the minimum field
2238 width.  The value is @code{'0'} if the @samp{0} flag was specified, and
2239 @code{' '} otherwise.
2240 @end table
2241 @end deftp
2244 @node Defining the Output Handler
2245 @subsection Defining the Output Handler
2247 Now let's look at how to define the handler and arginfo functions
2248 which are passed as arguments to @code{register_printf_function}.
2250 @strong{Compatibility Note:} The interface changed in GNU libc
2251 version 2.0.  Previously the third argument was of type
2252 @code{va_list *}.
2254 You should define your handler functions with a prototype like:
2256 @smallexample
2257 int @var{function} (FILE *stream, const struct printf_info *info,
2258                     const void *const *args)
2259 @end smallexample
2261 The @var{stream} argument passed to the handler function is the stream to
2262 which it should write output.
2264 The @var{info} argument is a pointer to a structure that contains
2265 information about the various options that were included with the
2266 conversion in the template string.  You should not modify this structure
2267 inside your handler function.  @xref{Conversion Specifier Options}, for
2268 a description of this data structure.
2270 @c The following changes some time back.  --drepper@gnu, 1996/11/14
2272 @c The @code{ap_pointer} argument is used to pass the tail of the variable
2273 @c argument list containing the values to be printed to your handler.
2274 @c Unlike most other functions that can be passed an explicit variable
2275 @c argument list, this is a @emph{pointer} to a @code{va_list}, rather than
2276 @c the @code{va_list} itself.  Thus, you should fetch arguments by
2277 @c means of @code{va_arg (*ap_pointer, @var{type})}.
2279 @c (Passing a pointer here allows the function that calls your handler
2280 @c function to update its own @code{va_list} variable to account for the
2281 @c arguments that your handler processes.  @xref{Variadic Functions}.)
2283 The @var{args} is a vector of pointers to the arguments data.
2284 The number of arguments was determined by calling the argument
2285 information function provided by the user.
2287 Your handler function should return a value just like @code{printf}
2288 does: it should return the number of characters it has written, or a
2289 negative value to indicate an error.
2291 @comment printf.h
2292 @comment GNU
2293 @deftp {Data Type} printf_function
2294 This is the data type that a handler function should have.
2295 @end deftp
2297 If you are going to use @w{@code{parse_printf_format}} in your
2298 application, you must also define a function to pass as the
2299 @var{arginfo-function} argument for each new conversion you install with
2300 @code{register_printf_function}.
2302 You have to define these functions with a prototype like:
2304 @smallexample
2305 int @var{function} (const struct printf_info *info,
2306                     size_t n, int *argtypes)
2307 @end smallexample
2309 The return value from the function should be the number of arguments the
2310 conversion expects.  The function should also fill in no more than
2311 @var{n} elements of the @var{argtypes} array with information about the
2312 types of each of these arguments.  This information is encoded using the
2313 various @samp{PA_} macros.  (You will notice that this is the same
2314 calling convention @code{parse_printf_format} itself uses.)
2316 @comment printf.h
2317 @comment GNU
2318 @deftp {Data Type} printf_arginfo_function
2319 This type is used to describe functions that return information about
2320 the number and type of arguments used by a conversion specifier.
2321 @end deftp
2323 @node Printf Extension Example
2324 @subsection @code{printf} Extension Example
2326 Here is an example showing how to define a @code{printf} handler function.
2327 This program defines a data structure called a @code{Widget} and
2328 defines the @samp{%W} conversion to print information about @w{@code{Widget *}}
2329 arguments, including the pointer value and the name stored in the data
2330 structure.  The @samp{%W} conversion supports the minimum field width and
2331 left-justification options, but ignores everything else.
2333 @smallexample
2334 @include rprintf.c.texi
2335 @end smallexample
2337 The output produced by this program looks like:
2339 @smallexample
2340 |<Widget 0xffeffb7c: mywidget>|
2341 |      <Widget 0xffeffb7c: mywidget>|
2342 |<Widget 0xffeffb7c: mywidget>      |
2343 @end smallexample
2345 @node Predefined Printf Handlers
2346 @subsection Predefined @code{printf} Handlers
2348 The GNU libc also contains a concrete and useful application of the
2349 @code{printf} handler extension.  There are two functions available
2350 which implement a special way to print floating-point numbers.
2352 @comment printf.h
2353 @comment GNU
2354 @deftypefun int printf_size (FILE *@var{fp}, const struct printf_info *@var{info}, const void *const *@var{args})
2355 Print a given floating point number as for the format @code{%f} except
2356 that there is a postfix character indicating the divisor for the
2357 number to make this less than 1000.  There are two possible divisors:
2358 powers of 1024 or powers of 1000.  Which one is used depends on the
2359 format character specified while registered this handler.  If the
2360 character is of lower case, 1024 is used.  For upper case characters,
2361 1000 is used.
2363 The postfix tag corresponds to bytes, kilobytes, megabytes, gigabytes,
2364 etc.  The full table is:
2366 @ifinfo
2367 @multitable @hsep @vsep {' '} {2^10 (1024)} {zetta} {Upper} {10^24 (1000)}
2368 @item low @tab Multiplier  @tab From  @tab Upper @tab Multiplier
2369 @item ' ' @tab 1           @tab       @tab ' '   @tab 1
2370 @item k   @tab 2^10 (1024) @tab kilo  @tab K     @tab 10^3 (1000)
2371 @item m   @tab 2^20        @tab mega  @tab M     @tab 10^6
2372 @item g   @tab 2^30        @tab giga  @tab G     @tab 10^9
2373 @item t   @tab 2^40        @tab tera  @tab T     @tab 10^12
2374 @item p   @tab 2^50        @tab peta  @tab P     @tab 10^15
2375 @item e   @tab 2^60        @tab exa   @tab E     @tab 10^18
2376 @item z   @tab 2^70        @tab zetta @tab Z     @tab 10^21
2377 @item y   @tab 2^80        @tab yotta @tab Y     @tab 10^24
2378 @end multitable
2379 @end ifinfo
2380 @iftex
2381 @tex
2382 \hbox to\hsize{\hfil\vbox{\offinterlineskip
2383 \hrule
2384 \halign{\strut#& \vrule#\tabskip=1em plus2em& {\tt#}\hfil& \vrule#& #\hfil& \vrule#& #\hfil& \vrule#& {\tt#}\hfil& \vrule#& #\hfil& \vrule#\tabskip=0pt\cr
2385 \noalign{\hrule}
2386 \omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
2387 && \omit low && Multiplier && From && \omit Upper && Multiplier &\cr
2388 \omit&height2pt&\omit&&\omit&&\omit&&\omit&&\omit&\cr
2389 \noalign{\hrule}
2390 && {\tt\char32} &&  1 && && {\tt\char32} && 1 &\cr
2391 && k && $2^{10} = 1024$ && kilo && K && $10^3 = 1000$ &\cr
2392 && m && $2^{20}$ && mega && M && $10^6$ &\cr
2393 && g && $2^{30}$ && giga && G && $10^9$ &\cr
2394 && t && $2^{40}$ && tera && T && $10^{12}$ &\cr
2395 && p && $2^{50}$ && peta && P && $10^{15}$ &\cr
2396 && e && $2^{60}$ && exa && E && $10^{18}$ &\cr
2397 && z && $2^{70}$ && zetta && Z && $10^{21}$ &\cr
2398 && y && $2^{80}$ && yotta && Y && $10^{24}$ &\cr
2399 \noalign{\hrule}}}\hfil}
2400 @end tex
2401 @end iftex
2403 The default precision is 3, i.e., 1024 is printed with a lower-case
2404 format character as if it were @code{%.3fk} and will yield @code{1.000k}.
2405 @end deftypefun
2407 Due to the requirements of @code{register_printf_function} we must also
2408 provide the function which returns information about the arguments.
2410 @comment printf.h
2411 @comment GNU
2412 @deftypefun int printf_size_info (const struct printf_info *@var{info}, size_t @var{n}, int *@var{argtypes})
2413 This function will return in @var{argtypes} the information about the
2414 used parameters in the way the @code{vfprintf} implementation expects
2415 it.  The format always takes one argument.
2416 @end deftypefun
2418 To use these functions both functions must be registered with a call like
2420 @smallexample
2421 register_printf_function ('B', printf_size, printf_size_info);
2422 @end smallexample
2424 Here we register the functions to print numbers as powers of 1000 since
2425 the format character @code{'B'} is an upper-case character.  If we
2426 would additionally use @code{'b'} in a line like
2428 @smallexample
2429 register_printf_function ('b', printf_size, printf_size_info);
2430 @end smallexample
2432 @noindent
2433 we could also print using a power of 1024.  Please note that all that is
2434 different in these two lines is the format specifier.  The
2435 @code{printf_size} function knows about the difference between lower and upper
2436 case format specifiers.
2438 The use of @code{'B'} and @code{'b'} is no coincidence.  Rather it is
2439 the preferred way to use this functionality since it is available on
2440 some other systems which also use format specifiers.
2442 @node Formatted Input
2443 @section Formatted Input
2445 @cindex formatted input from a stream
2446 @cindex reading from a stream, formatted
2447 @cindex format string, for @code{scanf}
2448 @cindex template, for @code{scanf}
2449 The functions described in this section (@code{scanf} and related
2450 functions) provide facilities for formatted input analogous to the
2451 formatted output facilities.  These functions provide a mechanism for
2452 reading arbitrary values under the control of a @dfn{format string} or
2453 @dfn{template string}.
2455 @menu
2456 * Formatted Input Basics::      Some basics to get you started.
2457 * Input Conversion Syntax::     Syntax of conversion specifications.
2458 * Table of Input Conversions::  Summary of input conversions and what they do.
2459 * Numeric Input Conversions::   Details of conversions for reading numbers.
2460 * String Input Conversions::    Details of conversions for reading strings.
2461 * Dynamic String Input::        String conversions that @code{malloc} the buffer.
2462 * Other Input Conversions::     Details of miscellaneous other conversions.
2463 * Formatted Input Functions::   Descriptions of the actual functions.
2464 * Variable Arguments Input::    @code{vscanf} and friends.
2465 @end menu
2467 @node Formatted Input Basics
2468 @subsection Formatted Input Basics
2470 Calls to @code{scanf} are superficially similar to calls to
2471 @code{printf} in that arbitrary arguments are read under the control of
2472 a template string.  While the syntax of the conversion specifications in
2473 the template is very similar to that for @code{printf}, the
2474 interpretation of the template is oriented more towards free-format
2475 input and simple pattern matching, rather than fixed-field formatting.
2476 For example, most @code{scanf} conversions skip over any amount of
2477 ``white space'' (including spaces, tabs, and newlines) in the input
2478 file, and there is no concept of precision for the numeric input
2479 conversions as there is for the corresponding output conversions.
2480 Ordinarily, non-whitespace characters in the template are expected to
2481 match characters in the input stream exactly, but a matching failure is
2482 distinct from an input error on the stream.
2483 @cindex conversion specifications (@code{scanf})
2485 Another area of difference between @code{scanf} and @code{printf} is
2486 that you must remember to supply pointers rather than immediate values
2487 as the optional arguments to @code{scanf}; the values that are read are
2488 stored in the objects that the pointers point to.  Even experienced
2489 programmers tend to forget this occasionally, so if your program is
2490 getting strange errors that seem to be related to @code{scanf}, you
2491 might want to double-check this.
2493 When a @dfn{matching failure} occurs, @code{scanf} returns immediately,
2494 leaving the first non-matching character as the next character to be
2495 read from the stream.  The normal return value from @code{scanf} is the
2496 number of values that were assigned, so you can use this to determine if
2497 a matching error happened before all the expected values were read.
2498 @cindex matching failure, in @code{scanf}
2500 The @code{scanf} function is typically used for things like reading in
2501 the contents of tables.  For example, here is a function that uses
2502 @code{scanf} to initialize an array of @code{double}:
2504 @smallexample
2505 void
2506 readarray (double *array, int n)
2508   int i;
2509   for (i=0; i<n; i++)
2510     if (scanf (" %lf", &(array[i])) != 1)
2511       invalid_input_error ();
2513 @end smallexample
2515 The formatted input functions are not used as frequently as the
2516 formatted output functions.  Partly, this is because it takes some care
2517 to use them properly.  Another reason is that it is difficult to recover
2518 from a matching error.
2520 If you are trying to read input that doesn't match a single, fixed
2521 pattern, you may be better off using a tool such as Flex to generate a
2522 lexical scanner, or Bison to generate a parser, rather than using
2523 @code{scanf}.  For more information about these tools, see @ref{, , ,
2524 flex.info, Flex: The Lexical Scanner Generator}, and @ref{, , ,
2525 bison.info, The Bison Reference Manual}.
2527 @node Input Conversion Syntax
2528 @subsection Input Conversion Syntax
2530 A @code{scanf} template string is a string that contains ordinary
2531 multibyte characters interspersed with conversion specifications that
2532 start with @samp{%}.
2534 Any whitespace character (as defined by the @code{isspace} function;
2535 @pxref{Classification of Characters}) in the template causes any number
2536 of whitespace characters in the input stream to be read and discarded.
2537 The whitespace characters that are matched need not be exactly the same
2538 whitespace characters that appear in the template string.  For example,
2539 write @samp{ , } in the template to recognize a comma with optional
2540 whitespace before and after.
2542 Other characters in the template string that are not part of conversion
2543 specifications must match characters in the input stream exactly; if
2544 this is not the case, a matching failure occurs.
2546 The conversion specifications in a @code{scanf} template string
2547 have the general form:
2549 @smallexample
2550 % @var{flags} @var{width} @var{type} @var{conversion}
2551 @end smallexample
2553 In more detail, an input conversion specification consists of an initial
2554 @samp{%} character followed in sequence by:
2556 @itemize @bullet
2557 @item
2558 An optional @dfn{flag character} @samp{*}, which says to ignore the text
2559 read for this specification.  When @code{scanf} finds a conversion
2560 specification that uses this flag, it reads input as directed by the
2561 rest of the conversion specification, but it discards this input, does
2562 not use a pointer argument, and does not increment the count of
2563 successful assignments.
2564 @cindex flag character (@code{scanf})
2566 @item
2567 An optional flag character @samp{a} (valid with string conversions only)
2568 which requests allocation of a buffer long enough to store the string in.
2569 (This is a GNU extension.)
2570 @xref{Dynamic String Input}.
2572 @item
2573 An optional decimal integer that specifies the @dfn{maximum field
2574 width}.  Reading of characters from the input stream stops either when
2575 this maximum is reached or when a non-matching character is found,
2576 whichever happens first.  Most conversions discard initial whitespace
2577 characters (those that don't are explicitly documented), and these
2578 discarded characters don't count towards the maximum field width.
2579 String input conversions store a null character to mark the end of the
2580 input; the maximum field width does not include this terminator.
2581 @cindex maximum field width (@code{scanf})
2583 @item
2584 An optional @dfn{type modifier character}.  For example, you can
2585 specify a type modifier of @samp{l} with integer conversions such as
2586 @samp{%d} to specify that the argument is a pointer to a @code{long int}
2587 rather than a pointer to an @code{int}.
2588 @cindex type modifier character (@code{scanf})
2590 @item
2591 A character that specifies the conversion to be applied.
2592 @end itemize
2594 The exact options that are permitted and how they are interpreted vary
2595 between the different conversion specifiers.  See the descriptions of the
2596 individual conversions for information about the particular options that
2597 they allow.
2599 With the @samp{-Wformat} option, the GNU C compiler checks calls to
2600 @code{scanf} and related functions.  It examines the format string and
2601 verifies that the correct number and types of arguments are supplied.
2602 There is also a GNU C syntax to tell the compiler that a function you
2603 write uses a @code{scanf}-style format string.
2604 @xref{Function Attributes, , Declaring Attributes of Functions,
2605 gcc.info, Using GNU CC}, for more information.
2607 @node Table of Input Conversions
2608 @subsection Table of Input Conversions
2609 @cindex input conversions, for @code{scanf}
2611 Here is a table that summarizes the various conversion specifications:
2613 @table @asis
2614 @item @samp{%d}
2615 Matches an optionally signed integer written in decimal.  @xref{Numeric
2616 Input Conversions}.
2618 @item @samp{%i}
2619 Matches an optionally signed integer in any of the formats that the C
2620 language defines for specifying an integer constant.  @xref{Numeric
2621 Input Conversions}.
2623 @item @samp{%o}
2624 Matches an unsigned integer written in octal radix.
2625 @xref{Numeric Input Conversions}.
2627 @item @samp{%u}
2628 Matches an unsigned integer written in decimal radix.
2629 @xref{Numeric Input Conversions}.
2631 @item @samp{%x}, @samp{%X}
2632 Matches an unsigned integer written in hexadecimal radix.
2633 @xref{Numeric Input Conversions}.
2635 @item @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, @samp{%G}
2636 Matches an optionally signed floating-point number.  @xref{Numeric Input
2637 Conversions}.
2639 @item @samp{%s}
2640 Matches a string containing only non-whitespace characters.
2641 @xref{String Input Conversions}.
2643 @item @samp{%[}
2644 Matches a string of characters that belong to a specified set.
2645 @xref{String Input Conversions}.
2647 @item @samp{%c}
2648 Matches a string of one or more characters; the number of characters
2649 read is controlled by the maximum field width given for the conversion.
2650 @xref{String Input Conversions}.
2652 @item @samp{%p}
2653 Matches a pointer value in the same implementation-defined format used
2654 by the @samp{%p} output conversion for @code{printf}.  @xref{Other Input
2655 Conversions}.
2657 @item @samp{%n}
2658 This conversion doesn't read any characters; it records the number of
2659 characters read so far by this call.  @xref{Other Input Conversions}.
2661 @item @samp{%%}
2662 This matches a literal @samp{%} character in the input stream.  No
2663 corresponding argument is used.  @xref{Other Input Conversions}.
2664 @end table
2666 If the syntax of a conversion specification is invalid, the behavior is
2667 undefined.  If there aren't enough function arguments provided to supply
2668 addresses for all the conversion specifications in the template strings
2669 that perform assignments, or if the arguments are not of the correct
2670 types, the behavior is also undefined.  On the other hand, extra
2671 arguments are simply ignored.
2673 @node Numeric Input Conversions
2674 @subsection Numeric Input Conversions
2676 This section describes the @code{scanf} conversions for reading numeric
2677 values.
2679 The @samp{%d} conversion matches an optionally signed integer in decimal
2680 radix.  The syntax that is recognized is the same as that for the
2681 @code{strtol} function (@pxref{Parsing of Integers}) with the value
2682 @code{10} for the @var{base} argument.
2684 The @samp{%i} conversion matches an optionally signed integer in any of
2685 the formats that the C language defines for specifying an integer
2686 constant.  The syntax that is recognized is the same as that for the
2687 @code{strtol} function (@pxref{Parsing of Integers}) with the value
2688 @code{0} for the @var{base} argument.  (You can print integers in this
2689 syntax with @code{printf} by using the @samp{#} flag character with the
2690 @samp{%x}, @samp{%o}, or @samp{%d} conversion.  @xref{Integer Conversions}.)
2692 For example, any of the strings @samp{10}, @samp{0xa}, or @samp{012}
2693 could be read in as integers under the @samp{%i} conversion.  Each of
2694 these specifies a number with decimal value @code{10}.
2696 The @samp{%o}, @samp{%u}, and @samp{%x} conversions match unsigned
2697 integers in octal, decimal, and hexadecimal radices, respectively.  The
2698 syntax that is recognized is the same as that for the @code{strtoul}
2699 function (@pxref{Parsing of Integers}) with the appropriate value
2700 (@code{8}, @code{10}, or @code{16}) for the @var{base} argument.
2702 The @samp{%X} conversion is identical to the @samp{%x} conversion.  They
2703 both permit either uppercase or lowercase letters to be used as digits.
2705 The default type of the corresponding argument for the @code{%d} and
2706 @code{%i} conversions is @code{int *}, and @code{unsigned int *} for the
2707 other integer conversions.  You can use the following type modifiers to
2708 specify other sizes of integer:
2710 @table @samp
2711 @item hh
2712 Specifies that the argument is a @code{signed char *} or @code{unsigned
2713 char *}.
2715 This modifier was introduced in @w{ISO C99}.
2717 @item h
2718 Specifies that the argument is a @code{short int *} or @code{unsigned
2719 short int *}.
2721 @item j
2722 Specifies that the argument is a @code{intmax_t *} or @code{uintmax_t *}.
2724 This modifier was introduced in @w{ISO C99}.
2726 @item l
2727 Specifies that the argument is a @code{long int *} or @code{unsigned
2728 long int *}.  Two @samp{l} characters is like the @samp{L} modifier, below.
2730 @need 100
2731 @item ll
2732 @itemx L
2733 @itemx q
2734 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
2735 GNU C compiler.  For systems that don't provide extra-long integers, this
2736 is the same as @code{long int}.)
2738 The @samp{q} modifier is another name for the same thing, which comes
2739 from 4.4 BSD; a @w{@code{long long int}} is sometimes called a ``quad''
2740 @code{int}.
2742 @item t
2743 Specifies that the argument is a @code{ptrdiff_t *}.
2745 This modifier was introduced in @w{ISO C99}.
2747 @item z
2748 Specifies that the argument is a @code{size_t *}.
2750 This modifier was introduced in @w{ISO C99}.
2751 @end table
2753 All of the @samp{%e}, @samp{%f}, @samp{%g}, @samp{%E}, and @samp{%G}
2754 input conversions are interchangeable.  They all match an optionally
2755 signed floating point number, in the same syntax as for the
2756 @code{strtod} function (@pxref{Parsing of Floats}).
2758 For the floating-point input conversions, the default argument type is
2759 @code{float *}.  (This is different from the corresponding output
2760 conversions, where the default type is @code{double}; remember that
2761 @code{float} arguments to @code{printf} are converted to @code{double}
2762 by the default argument promotions, but @code{float *} arguments are
2763 not promoted to @code{double *}.)  You can specify other sizes of float
2764 using these type modifiers:
2766 @table @samp
2767 @item l
2768 Specifies that the argument is of type @code{double *}.
2770 @item L
2771 Specifies that the argument is of type @code{long double *}.
2772 @end table
2774 For all the above number parsing formats there is an additional optional
2775 flag @samp{'}.  When this flag is given the @code{scanf} function
2776 expects the number represented in the input string to be formatted
2777 according to the grouping rules of the currently selected locale
2778 (@pxref{General Numeric}).
2780 If the @code{"C"} or @code{"POSIX"} locale is selected there is no
2781 difference.  But for a locale which specifies values for the appropriate
2782 fields in the locale the input must have the correct form in the input.
2783 Otherwise the longest prefix with a correct form is processed.
2785 @node String Input Conversions
2786 @subsection String Input Conversions
2788 This section describes the @code{scanf} input conversions for reading
2789 string and character values: @samp{%s}, @samp{%[}, and @samp{%c}.
2791 You have two options for how to receive the input from these
2792 conversions:
2794 @itemize @bullet
2795 @item
2796 Provide a buffer to store it in.  This is the default.  You
2797 should provide an argument of type @code{char *}.
2799 @strong{Warning:} To make a robust program, you must make sure that the
2800 input (plus its terminating null) cannot possibly exceed the size of the
2801 buffer you provide.  In general, the only way to do this is to specify a
2802 maximum field width one less than the buffer size.  @strong{If you
2803 provide the buffer, always specify a maximum field width to prevent
2804 overflow.}
2806 @item
2807 Ask @code{scanf} to allocate a big enough buffer, by specifying the
2808 @samp{a} flag character.  This is a GNU extension.  You should provide
2809 an argument of type @code{char **} for the buffer address to be stored
2810 in.  @xref{Dynamic String Input}.
2811 @end itemize
2813 The @samp{%c} conversion is the simplest: it matches a fixed number of
2814 characters, always.  The maximum field width says how many characters to
2815 read; if you don't specify the maximum, the default is 1.  This
2816 conversion doesn't append a null character to the end of the text it
2817 reads.  It also does not skip over initial whitespace characters.  It
2818 reads precisely the next @var{n} characters, and fails if it cannot get
2819 that many.  Since there is always a maximum field width with @samp{%c}
2820 (whether specified, or 1 by default), you can always prevent overflow by
2821 making the buffer long enough.
2823 The @samp{%s} conversion matches a string of non-whitespace characters.
2824 It skips and discards initial whitespace, but stops when it encounters
2825 more whitespace after having read something.  It stores a null character
2826 at the end of the text that it reads.
2828 For example, reading the input:
2830 @smallexample
2831  hello, world
2832 @end smallexample
2834 @noindent
2835 with the conversion @samp{%10c} produces @code{" hello, wo"}, but
2836 reading the same input with the conversion @samp{%10s} produces
2837 @code{"hello,"}.
2839 @strong{Warning:} If you do not specify a field width for @samp{%s},
2840 then the number of characters read is limited only by where the next
2841 whitespace character appears.  This almost certainly means that invalid
2842 input can make your program crash---which is a bug.
2844 To read in characters that belong to an arbitrary set of your choice,
2845 use the @samp{%[} conversion.  You specify the set between the @samp{[}
2846 character and a following @samp{]} character, using the same syntax used
2847 in regular expressions.  As special cases:
2849 @itemize @bullet
2850 @item
2851 A literal @samp{]} character can be specified as the first character
2852 of the set.
2854 @item
2855 An embedded @samp{-} character (that is, one that is not the first or
2856 last character of the set) is used to specify a range of characters.
2858 @item
2859 If a caret character @samp{^} immediately follows the initial @samp{[},
2860 then the set of allowed input characters is the everything @emph{except}
2861 the characters listed.
2862 @end itemize
2864 The @samp{%[} conversion does not skip over initial whitespace
2865 characters.
2867 Here are some examples of @samp{%[} conversions and what they mean:
2869 @table @samp
2870 @item %25[1234567890]
2871 Matches a string of up to 25 digits.
2873 @item %25[][]
2874 Matches a string of up to 25 square brackets.
2876 @item %25[^ \f\n\r\t\v]
2877 Matches a string up to 25 characters long that doesn't contain any of
2878 the standard whitespace characters.  This is slightly different from
2879 @samp{%s}, because if the input begins with a whitespace character,
2880 @samp{%[} reports a matching failure while @samp{%s} simply discards the
2881 initial whitespace.
2883 @item %25[a-z]
2884 Matches up to 25 lowercase characters.
2885 @end table
2887 One more reminder: the @samp{%s} and @samp{%[} conversions are
2888 @strong{dangerous} if you don't specify a maximum width or use the
2889 @samp{a} flag, because input too long would overflow whatever buffer you
2890 have provided for it.  No matter how long your buffer is, a user could
2891 supply input that is longer.  A well-written program reports invalid
2892 input with a comprehensible error message, not with a crash.
2894 @node Dynamic String Input
2895 @subsection Dynamically Allocating String Conversions
2897 A GNU extension to formatted input lets you safely read a string with no
2898 maximum size.  Using this feature, you don't supply a buffer; instead,
2899 @code{scanf} allocates a buffer big enough to hold the data and gives
2900 you its address.  To use this feature, write @samp{a} as a flag
2901 character, as in @samp{%as} or @samp{%a[0-9a-z]}.
2903 The pointer argument you supply for where to store the input should have
2904 type @code{char **}.  The @code{scanf} function allocates a buffer and
2905 stores its address in the word that the argument points to.  You should
2906 free the buffer with @code{free} when you no longer need it.
2908 Here is an example of using the @samp{a} flag with the @samp{%[@dots{}]}
2909 conversion specification to read a ``variable assignment'' of the form
2910 @samp{@var{variable} = @var{value}}.
2912 @smallexample
2914   char *variable, *value;
2916   if (2 > scanf ("%a[a-zA-Z0-9] = %a[^\n]\n",
2917                  &variable, &value))
2918     @{
2919       invalid_input_error ();
2920       return 0;
2921     @}
2923   @dots{}
2925 @end smallexample
2927 @node Other Input Conversions
2928 @subsection Other Input Conversions
2930 This section describes the miscellaneous input conversions.
2932 The @samp{%p} conversion is used to read a pointer value.  It recognizes
2933 the same syntax used by the @samp{%p} output conversion for
2934 @code{printf} (@pxref{Other Output Conversions}); that is, a hexadecimal
2935 number just as the @samp{%x} conversion accepts.  The corresponding
2936 argument should be of type @code{void **}; that is, the address of a
2937 place to store a pointer.
2939 The resulting pointer value is not guaranteed to be valid if it was not
2940 originally written during the same program execution that reads it in.
2942 The @samp{%n} conversion produces the number of characters read so far
2943 by this call.  The corresponding argument should be of type @code{int *}.
2944 This conversion works in the same way as the @samp{%n} conversion for
2945 @code{printf}; see @ref{Other Output Conversions}, for an example.
2947 The @samp{%n} conversion is the only mechanism for determining the
2948 success of literal matches or conversions with suppressed assignments.
2949 If the @samp{%n} follows the locus of a matching failure, then no value
2950 is stored for it since @code{scanf} returns before processing the
2951 @samp{%n}.  If you store @code{-1} in that argument slot before calling
2952 @code{scanf}, the presence of @code{-1} after @code{scanf} indicates an
2953 error occurred before the @samp{%n} was reached.
2955 Finally, the @samp{%%} conversion matches a literal @samp{%} character
2956 in the input stream, without using an argument.  This conversion does
2957 not permit any flags, field width, or type modifier to be specified.
2959 @node Formatted Input Functions
2960 @subsection Formatted Input Functions
2962 Here are the descriptions of the functions for performing formatted
2963 input.
2964 Prototypes for these functions are in the header file @file{stdio.h}.
2965 @pindex stdio.h
2967 @comment stdio.h
2968 @comment ISO
2969 @deftypefun int scanf (const char *@var{template}, @dots{})
2970 The @code{scanf} function reads formatted input from the stream
2971 @code{stdin} under the control of the template string @var{template}.
2972 The optional arguments are pointers to the places which receive the
2973 resulting values.
2975 The return value is normally the number of successful assignments.  If
2976 an end-of-file condition is detected before any matches are performed,
2977 including matches against whitespace and literal characters in the
2978 template, then @code{EOF} is returned.
2979 @end deftypefun
2981 @comment stdio.h
2982 @comment ISO
2983 @deftypefun int fscanf (FILE *@var{stream}, const char *@var{template}, @dots{})
2984 This function is just like @code{scanf}, except that the input is read
2985 from the stream @var{stream} instead of @code{stdin}.
2986 @end deftypefun
2988 @comment stdio.h
2989 @comment ISO
2990 @deftypefun int sscanf (const char *@var{s}, const char *@var{template}, @dots{})
2991 This is like @code{scanf}, except that the characters are taken from the
2992 null-terminated string @var{s} instead of from a stream.  Reaching the
2993 end of the string is treated as an end-of-file condition.
2995 The behavior of this function is undefined if copying takes place
2996 between objects that overlap---for example, if @var{s} is also given
2997 as an argument to receive a string read under control of the @samp{%s}
2998 conversion.
2999 @end deftypefun
3001 @node Variable Arguments Input
3002 @subsection Variable Arguments Input Functions
3004 The functions @code{vscanf} and friends are provided so that you can
3005 define your own variadic @code{scanf}-like functions that make use of
3006 the same internals as the built-in formatted output functions.
3007 These functions are analogous to the @code{vprintf} series of output
3008 functions.  @xref{Variable Arguments Output}, for important
3009 information on how to use them.
3011 @strong{Portability Note:} The functions listed in this section are GNU
3012 extensions.
3014 @comment stdio.h
3015 @comment GNU
3016 @deftypefun int vscanf (const char *@var{template}, va_list @var{ap})
3017 This function is similar to @code{scanf}, but instead of taking
3018 a variable number of arguments directly, it takes an argument list
3019 pointer @var{ap} of type @code{va_list} (@pxref{Variadic Functions}).
3020 @end deftypefun
3022 @comment stdio.h
3023 @comment GNU
3024 @deftypefun int vfscanf (FILE *@var{stream}, const char *@var{template}, va_list @var{ap})
3025 This is the equivalent of @code{fscanf} with the variable argument list
3026 specified directly as for @code{vscanf}.
3027 @end deftypefun
3029 @comment stdio.h
3030 @comment GNU
3031 @deftypefun int vsscanf (const char *@var{s}, const char *@var{template}, va_list @var{ap})
3032 This is the equivalent of @code{sscanf} with the variable argument list
3033 specified directly as for @code{vscanf}.
3034 @end deftypefun
3036 In GNU C, there is a special construct you can use to let the compiler
3037 know that a function uses a @code{scanf}-style format string.  Then it
3038 can check the number and types of arguments in each call to the
3039 function, and warn you when they do not match the format string.
3040 For details, @xref{Function Attributes, , Declaring Attributes of Functions,
3041 gcc.info, Using GNU CC}.
3043 @node EOF and Errors
3044 @section End-Of-File and Errors
3046 @cindex end of file, on a stream
3047 Many of the functions described in this chapter return the value of the
3048 macro @code{EOF} to indicate unsuccessful completion of the operation.
3049 Since @code{EOF} is used to report both end of file and random errors,
3050 it's often better to use the @code{feof} function to check explicitly
3051 for end of file and @code{ferror} to check for errors.  These functions
3052 check indicators that are part of the internal state of the stream
3053 object, indicators set if the appropriate condition was detected by a
3054 previous I/O operation on that stream.
3056 These symbols are declared in the header file @file{stdio.h}.
3057 @pindex stdio.h
3059 @comment stdio.h
3060 @comment ISO
3061 @deftypevr Macro int EOF
3062 This macro is an integer value that is returned by a number of functions
3063 to indicate an end-of-file condition, or some other error situation.
3064 With the GNU library, @code{EOF} is @code{-1}.  In other libraries, its
3065 value may be some other negative number.
3066 @end deftypevr
3068 @comment stdio.h
3069 @comment ISO
3070 @deftypefun int feof (FILE *@var{stream})
3071 The @code{feof} function returns nonzero if and only if the end-of-file
3072 indicator for the stream @var{stream} is set.
3073 @end deftypefun
3075 @comment stdio.h
3076 @comment ISO
3077 @deftypefun int ferror (FILE *@var{stream})
3078 The @code{ferror} function returns nonzero if and only if the error
3079 indicator for the stream @var{stream} is set, indicating that an error
3080 has occurred on a previous operation on the stream.
3081 @end deftypefun
3083 In addition to setting the error indicator associated with the stream,
3084 the functions that operate on streams also set @code{errno} in the same
3085 way as the corresponding low-level functions that operate on file
3086 descriptors.  For example, all of the functions that perform output to a
3087 stream---such as @code{fputc}, @code{printf}, and @code{fflush}---are
3088 implemented in terms of @code{write}, and all of the @code{errno} error
3089 conditions defined for @code{write} are meaningful for these functions.
3090 For more information about the descriptor-level I/O functions, see
3091 @ref{Low-Level I/O}.
3093 @node Error Recovery
3094 @section Recovering from errors
3096 You may explicitly clear the error and EOF flags with the @code{clearerr}
3097 function.
3099 @comment stdio.h
3100 @comment ISO
3101 @deftypefun void clearerr (FILE *@var{stream})
3102 This function clears the end-of-file and error indicators for the
3103 stream @var{stream}.
3105 The file positioning functions (@pxref{File Positioning}) also clear the
3106 end-of-file indicator for the stream.
3107 @end deftypefun
3109 Note that it is @emph{not} correct to just clear the error flag and retry
3110 a failed stream operation.  After a failed write, any number of
3111 characters since the last buffer flush may have been committed to the
3112 file, while some buffered data may have been discarded.  Merely retrying
3113 can thus cause lost or repeated data.
3115 A failed read may leave the file pointer in an inappropriate position for
3116 a second try.  In both cases, you should seek to a known position before
3117 retrying.
3119 Most errors that can happen are not recoverable --- a second try will
3120 always fail again in the same way.  So usually it is best to give up and
3121 report the error to the user, rather than install complicated recovery
3122 logic.
3124 One important exception is @code{EINTR} (@pxref{Interrupted Primitives}).
3125 Many stream I/O implementations will treat it as an ordinary error, which
3126 can be quite inconvenient.  You can avoid this hassle by installing all
3127 signals with the @code{SA_RESTART} flag.
3129 For similar reasons, setting nonblocking I/O on a stream's file
3130 descriptor is not usually advisable.
3132 @node Binary Streams
3133 @section Text and Binary Streams
3135 The GNU system and other POSIX-compatible operating systems organize all
3136 files as uniform sequences of characters.  However, some other systems
3137 make a distinction between files containing text and files containing
3138 binary data, and the input and output facilities of @w{ISO C} provide for
3139 this distinction.  This section tells you how to write programs portable
3140 to such systems.
3142 @cindex text stream
3143 @cindex binary stream
3144 When you open a stream, you can specify either a @dfn{text stream} or a
3145 @dfn{binary stream}.  You indicate that you want a binary stream by
3146 specifying the @samp{b} modifier in the @var{opentype} argument to
3147 @code{fopen}; see @ref{Opening Streams}.  Without this
3148 option, @code{fopen} opens the file as a text stream.
3150 Text and binary streams differ in several ways:
3152 @itemize @bullet
3153 @item
3154 The data read from a text stream is divided into @dfn{lines} which are
3155 terminated by newline (@code{'\n'}) characters, while a binary stream is
3156 simply a long series of characters.  A text stream might on some systems
3157 fail to handle lines more than 254 characters long (including the
3158 terminating newline character).
3159 @cindex lines (in a text file)
3161 @item
3162 On some systems, text files can contain only printing characters,
3163 horizontal tab characters, and newlines, and so text streams may not
3164 support other characters.  However, binary streams can handle any
3165 character value.
3167 @item
3168 Space characters that are written immediately preceding a newline
3169 character in a text stream may disappear when the file is read in again.
3171 @item
3172 More generally, there need not be a one-to-one mapping between
3173 characters that are read from or written to a text stream, and the
3174 characters in the actual file.
3175 @end itemize
3177 Since a binary stream is always more capable and more predictable than a
3178 text stream, you might wonder what purpose text streams serve.  Why not
3179 simply always use binary streams?  The answer is that on these operating
3180 systems, text and binary streams use different file formats, and the
3181 only way to read or write ``an ordinary file of text'' that can work
3182 with other text-oriented programs is through a text stream.
3184 In the GNU library, and on all POSIX systems, there is no difference
3185 between text streams and binary streams.  When you open a stream, you
3186 get the same kind of stream regardless of whether you ask for binary.
3187 This stream can handle any file content, and has none of the
3188 restrictions that text streams sometimes have.
3190 @node File Positioning
3191 @section File Positioning
3192 @cindex file positioning on a stream
3193 @cindex positioning a stream
3194 @cindex seeking on a stream
3196 The @dfn{file position} of a stream describes where in the file the
3197 stream is currently reading or writing.  I/O on the stream advances the
3198 file position through the file.  In the GNU system, the file position is
3199 represented as an integer, which counts the number of bytes from the
3200 beginning of the file.  @xref{File Position}.
3202 During I/O to an ordinary disk file, you can change the file position
3203 whenever you wish, so as to read or write any portion of the file.  Some
3204 other kinds of files may also permit this.  Files which support changing
3205 the file position are sometimes referred to as @dfn{random-access}
3206 files.
3208 You can use the functions in this section to examine or modify the file
3209 position indicator associated with a stream.  The symbols listed below
3210 are declared in the header file @file{stdio.h}.
3211 @pindex stdio.h
3213 @comment stdio.h
3214 @comment ISO
3215 @deftypefun {long int} ftell (FILE *@var{stream})
3216 This function returns the current file position of the stream
3217 @var{stream}.
3219 This function can fail if the stream doesn't support file positioning,
3220 or if the file position can't be represented in a @code{long int}, and
3221 possibly for other reasons as well.  If a failure occurs, a value of
3222 @code{-1} is returned.
3223 @end deftypefun
3225 @comment stdio.h
3226 @comment Unix98
3227 @deftypefun off_t ftello (FILE *@var{stream})
3228 The @code{ftello} function is similar to @code{ftell}, except that it
3229 returns a value of type @code{off_t}.  Systems which support this type
3230 use it to describe all file positions, unlike the POSIX specification
3231 which uses a long int.  The two are not necessarily the same size.
3232 Therefore, using ftell can lead to problems if the implementation is
3233 written on top of a POSIX compliant low-level I/O implementation, and using
3234 @code{ftello} is preferable whenever it is available.
3236 If this function fails it returns @code{(off_t) -1}.  This can happen due
3237 to missing support for file positioning or internal errors.  Otherwise
3238 the return value is the current file position.
3240 The function is an extension defined in the Unix Single Specification
3241 version 2.
3243 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3244 32 bit system this function is in fact @code{ftello64}.  I.e., the
3245 LFS interface transparently replaces the old interface.
3246 @end deftypefun
3248 @comment stdio.h
3249 @comment Unix98
3250 @deftypefun off64_t ftello64 (FILE *@var{stream})
3251 This function is similar to @code{ftello} with the only difference that
3252 the return value is of type @code{off64_t}.  This also requires that the
3253 stream @var{stream} was opened using either @code{fopen64},
3254 @code{freopen64}, or @code{tmpfile64} since otherwise the underlying
3255 file operations to position the file pointer beyond the @math{2^31}
3256 bytes limit might fail.
3258 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3259 bits machine this function is available under the name @code{ftello}
3260 and so transparently replaces the old interface.
3261 @end deftypefun
3263 @comment stdio.h
3264 @comment ISO
3265 @deftypefun int fseek (FILE *@var{stream}, long int @var{offset}, int @var{whence})
3266 The @code{fseek} function is used to change the file position of the
3267 stream @var{stream}.  The value of @var{whence} must be one of the
3268 constants @code{SEEK_SET}, @code{SEEK_CUR}, or @code{SEEK_END}, to
3269 indicate whether the @var{offset} is relative to the beginning of the
3270 file, the current file position, or the end of the file, respectively.
3272 This function returns a value of zero if the operation was successful,
3273 and a nonzero value to indicate failure.  A successful call also clears
3274 the end-of-file indicator of @var{stream} and discards any characters
3275 that were ``pushed back'' by the use of @code{ungetc}.
3277 @code{fseek} either flushes any buffered output before setting the file
3278 position or else remembers it so it will be written later in its proper
3279 place in the file.
3280 @end deftypefun
3282 @comment stdio.h
3283 @comment Unix98
3284 @deftypefun int fseeko (FILE *@var{stream}, off_t @var{offset}, int @var{whence})
3285 This function is similar to @code{fseek} but it corrects a problem with
3286 @code{fseek} in a system with POSIX types.  Using a value of type
3287 @code{long int} for the offset is not compatible with POSIX.
3288 @code{fseeko} uses the correct type @code{off_t} for the @var{offset}
3289 parameter.
3291 For this reason it is a good idea to prefer @code{ftello} whenever it is
3292 available since its functionality is (if different at all) closer the
3293 underlying definition.
3295 The functionality and return value is the same as for @code{fseek}.
3297 The function is an extension defined in the Unix Single Specification
3298 version 2.
3300 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3301 32 bit system this function is in fact @code{fseeko64}.  I.e., the
3302 LFS interface transparently replaces the old interface.
3303 @end deftypefun
3305 @comment stdio.h
3306 @comment Unix98
3307 @deftypefun int fseeko64 (FILE *@var{stream}, off64_t @var{offset}, int @var{whence})
3308 This function is similar to @code{fseeko} with the only difference that
3309 the @var{offset} parameter is of type @code{off64_t}.  This also
3310 requires that the stream @var{stream} was opened using either
3311 @code{fopen64}, @code{freopen64}, or @code{tmpfile64} since otherwise
3312 the underlying file operations to position the file pointer beyond the
3313 @math{2^31} bytes limit might fail.
3315 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3316 bits machine this function is available under the name @code{fseeko}
3317 and so transparently replaces the old interface.
3318 @end deftypefun
3320 @strong{Portability Note:} In non-POSIX systems, @code{ftell},
3321 @code{ftello}, @code{fseek} and @code{fseeko} might work reliably only
3322 on binary streams.  @xref{Binary Streams}.
3324 The following symbolic constants are defined for use as the @var{whence}
3325 argument to @code{fseek}.  They are also used with the @code{lseek}
3326 function (@pxref{I/O Primitives}) and to specify offsets for file locks
3327 (@pxref{Control Operations}).
3329 @comment stdio.h
3330 @comment ISO
3331 @deftypevr Macro int SEEK_SET
3332 This is an integer constant which, when used as the @var{whence}
3333 argument to the @code{fseek} or @code{fseeko} function, specifies that
3334 the offset provided is relative to the beginning of the file.
3335 @end deftypevr
3337 @comment stdio.h
3338 @comment ISO
3339 @deftypevr Macro int SEEK_CUR
3340 This is an integer constant which, when used as the @var{whence}
3341 argument to the @code{fseek} or @code{fseeko} function, specifies that
3342 the offset provided is relative to the current file position.
3343 @end deftypevr
3345 @comment stdio.h
3346 @comment ISO
3347 @deftypevr Macro int SEEK_END
3348 This is an integer constant which, when used as the @var{whence}
3349 argument to the @code{fseek} or @code{fseeko} function, specifies that
3350 the offset provided is relative to the end of the file.
3351 @end deftypevr
3353 @comment stdio.h
3354 @comment ISO
3355 @deftypefun void rewind (FILE *@var{stream})
3356 The @code{rewind} function positions the stream @var{stream} at the
3357 beginning of the file.  It is equivalent to calling @code{fseek} or
3358 @code{fseeko} on the @var{stream} with an @var{offset} argument of
3359 @code{0L} and a @var{whence} argument of @code{SEEK_SET}, except that
3360 the return value is discarded and the error indicator for the stream is
3361 reset.
3362 @end deftypefun
3364 These three aliases for the @samp{SEEK_@dots{}} constants exist for the
3365 sake of compatibility with older BSD systems.  They are defined in two
3366 different header files: @file{fcntl.h} and @file{sys/file.h}.
3368 @table @code
3369 @comment sys/file.h
3370 @comment BSD
3371 @item L_SET
3372 @vindex L_SET
3373 An alias for @code{SEEK_SET}.
3375 @comment sys/file.h
3376 @comment BSD
3377 @item L_INCR
3378 @vindex L_INCR
3379 An alias for @code{SEEK_CUR}.
3381 @comment sys/file.h
3382 @comment BSD
3383 @item L_XTND
3384 @vindex L_XTND
3385 An alias for @code{SEEK_END}.
3386 @end table
3388 @node Portable Positioning
3389 @section Portable File-Position Functions
3391 On the GNU system, the file position is truly a character count.  You
3392 can specify any character count value as an argument to @code{fseek} or
3393 @code{fseeko} and get reliable results for any random access file.
3394 However, some @w{ISO C} systems do not represent file positions in this
3395 way.
3397 On some systems where text streams truly differ from binary streams, it
3398 is impossible to represent the file position of a text stream as a count
3399 of characters from the beginning of the file.  For example, the file
3400 position on some systems must encode both a record offset within the
3401 file, and a character offset within the record.
3403 As a consequence, if you want your programs to be portable to these
3404 systems, you must observe certain rules:
3406 @itemize @bullet
3407 @item
3408 The value returned from @code{ftell} on a text stream has no predictable
3409 relationship to the number of characters you have read so far.  The only
3410 thing you can rely on is that you can use it subsequently as the
3411 @var{offset} argument to @code{fseek} or @code{fseeko} to move back to
3412 the same file position.
3414 @item
3415 In a call to @code{fseek} or @code{fseeko} on a text stream, either the
3416 @var{offset} must be zero, or @var{whence} must be @code{SEEK_SET} and
3417 and the @var{offset} must be the result of an earlier call to @code{ftell}
3418 on the same stream.
3420 @item
3421 The value of the file position indicator of a text stream is undefined
3422 while there are characters that have been pushed back with @code{ungetc}
3423 that haven't been read or discarded.  @xref{Unreading}.
3424 @end itemize
3426 But even if you observe these rules, you may still have trouble for long
3427 files, because @code{ftell} and @code{fseek} use a @code{long int} value
3428 to represent the file position.  This type may not have room to encode
3429 all the file positions in a large file.  Using the @code{ftello} and
3430 @code{fseeko} functions might help here since the @code{off_t} type is
3431 expected to be able to hold all file position values but this still does
3432 not help to handle additional information which must be associated with
3433 a file position.
3435 So if you do want to support systems with peculiar encodings for the
3436 file positions, it is better to use the functions @code{fgetpos} and
3437 @code{fsetpos} instead.  These functions represent the file position
3438 using the data type @code{fpos_t}, whose internal representation varies
3439 from system to system.
3441 These symbols are declared in the header file @file{stdio.h}.
3442 @pindex stdio.h
3444 @comment stdio.h
3445 @comment ISO
3446 @deftp {Data Type} fpos_t
3447 This is the type of an object that can encode information about the
3448 file position of a stream, for use by the functions @code{fgetpos} and
3449 @code{fsetpos}.
3451 In the GNU system, @code{fpos_t} is equivalent to @code{off_t} or
3452 @code{long int}.  In other systems, it might have a different internal
3453 representation.
3455 When compiling with @code{_FILE_OFFSET_BITS == 64} on a 32 bit machine
3456 this type is in fact equivalent to @code{off64_t} since the LFS
3457 interface transparently replaced the old interface.
3458 @end deftp
3460 @comment stdio.h
3461 @comment Unix98
3462 @deftp {Data Type} fpos64_t
3463 This is the type of an object that can encode information about the
3464 file position of a stream, for use by the functions @code{fgetpos64} and
3465 @code{fsetpos64}.
3467 In the GNU system, @code{fpos64_t} is equivalent to @code{off64_t} or
3468 @code{long long int}.  In other systems, it might have a different internal
3469 representation.
3470 @end deftp
3472 @comment stdio.h
3473 @comment ISO
3474 @deftypefun int fgetpos (FILE *@var{stream}, fpos_t *@var{position})
3475 This function stores the value of the file position indicator for the
3476 stream @var{stream} in the @code{fpos_t} object pointed to by
3477 @var{position}.  If successful, @code{fgetpos} returns zero; otherwise
3478 it returns a nonzero value and stores an implementation-defined positive
3479 value in @code{errno}.
3481 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3482 32 bit system the function is in fact @code{fgetpos64}.  I.e., the LFS
3483 interface transparently replaced the old interface.
3484 @end deftypefun
3486 @comment stdio.h
3487 @comment Unix98
3488 @deftypefun int fgetpos64 (FILE *@var{stream}, fpos64_t *@var{position})
3489 This function is similar to @code{fgetpos} but the file position is
3490 returned in a variable of type @code{fpos64_t} to which @var{position}
3491 points.
3493 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3494 bits machine this function is available under the name @code{fgetpos}
3495 and so transparently replaces the old interface.
3496 @end deftypefun
3498 @comment stdio.h
3499 @comment ISO
3500 @deftypefun int fsetpos (FILE *@var{stream}, const fpos_t *@var{position})
3501 This function sets the file position indicator for the stream @var{stream}
3502 to the position @var{position}, which must have been set by a previous
3503 call to @code{fgetpos} on the same stream.  If successful, @code{fsetpos}
3504 clears the end-of-file indicator on the stream, discards any characters
3505 that were ``pushed back'' by the use of @code{ungetc}, and returns a value
3506 of zero.  Otherwise, @code{fsetpos} returns a nonzero value and stores
3507 an implementation-defined positive value in @code{errno}.
3509 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
3510 32 bit system the function is in fact @code{fsetpos64}.  I.e., the LFS
3511 interface transparently replaced the old interface.
3512 @end deftypefun
3514 @comment stdio.h
3515 @comment Unix98
3516 @deftypefun int fsetpos64 (FILE *@var{stream}, const fpos64_t *@var{position})
3517 This function is similar to @code{fsetpos} but the file position used
3518 for positioning is provided in a variable of type @code{fpos64_t} to
3519 which @var{position} points.
3521 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a 32
3522 bits machine this function is available under the name @code{fsetpos}
3523 and so transparently replaces the old interface.
3524 @end deftypefun
3526 @node Stream Buffering
3527 @section Stream Buffering
3529 @cindex buffering of streams
3530 Characters that are written to a stream are normally accumulated and
3531 transmitted asynchronously to the file in a block, instead of appearing
3532 as soon as they are output by the application program.  Similarly,
3533 streams often retrieve input from the host environment in blocks rather
3534 than on a character-by-character basis.  This is called @dfn{buffering}.
3536 If you are writing programs that do interactive input and output using
3537 streams, you need to understand how buffering works when you design the
3538 user interface to your program.  Otherwise, you might find that output
3539 (such as progress or prompt messages) doesn't appear when you intended
3540 it to, or displays some other unexpected behavior.
3542 This section deals only with controlling when characters are transmitted
3543 between the stream and the file or device, and @emph{not} with how
3544 things like echoing, flow control, and the like are handled on specific
3545 classes of devices.  For information on common control operations on
3546 terminal devices, see @ref{Low-Level Terminal Interface}.
3548 You can bypass the stream buffering facilities altogether by using the
3549 low-level input and output functions that operate on file descriptors
3550 instead.  @xref{Low-Level I/O}.
3552 @menu
3553 * Buffering Concepts::          Terminology is defined here.
3554 * Flushing Buffers::            How to ensure that output buffers are flushed.
3555 * Controlling Buffering::       How to specify what kind of buffering to use.
3556 @end menu
3558 @node Buffering Concepts
3559 @subsection Buffering Concepts
3561 There are three different kinds of buffering strategies:
3563 @itemize @bullet
3564 @item
3565 Characters written to or read from an @dfn{unbuffered} stream are
3566 transmitted individually to or from the file as soon as possible.
3567 @cindex unbuffered stream
3569 @item
3570 Characters written to a @dfn{line buffered} stream are transmitted to
3571 the file in blocks when a newline character is encountered.
3572 @cindex line buffered stream
3574 @item
3575 Characters written to or read from a @dfn{fully buffered} stream are
3576 transmitted to or from the file in blocks of arbitrary size.
3577 @cindex fully buffered stream
3578 @end itemize
3580 Newly opened streams are normally fully buffered, with one exception: a
3581 stream connected to an interactive device such as a terminal is
3582 initially line buffered.  @xref{Controlling Buffering}, for information
3583 on how to select a different kind of buffering.  Usually the automatic
3584 selection gives you the most convenient kind of buffering for the file
3585 or device you open.
3587 The use of line buffering for interactive devices implies that output
3588 messages ending in a newline will appear immediately---which is usually
3589 what you want.  Output that doesn't end in a newline might or might not
3590 show up immediately, so if you want them to appear immediately, you
3591 should flush buffered output explicitly with @code{fflush}, as described
3592 in @ref{Flushing Buffers}.
3594 @node Flushing Buffers
3595 @subsection Flushing Buffers
3597 @cindex flushing a stream
3598 @dfn{Flushing} output on a buffered stream means transmitting all
3599 accumulated characters to the file.  There are many circumstances when
3600 buffered output on a stream is flushed automatically:
3602 @itemize @bullet
3603 @item
3604 When you try to do output and the output buffer is full.
3606 @item
3607 When the stream is closed.  @xref{Closing Streams}.
3609 @item
3610 When the program terminates by calling @code{exit}.
3611 @xref{Normal Termination}.
3613 @item
3614 When a newline is written, if the stream is line buffered.
3616 @item
3617 Whenever an input operation on @emph{any} stream actually reads data
3618 from its file.
3619 @end itemize
3621 If you want to flush the buffered output at another time, call
3622 @code{fflush}, which is declared in the header file @file{stdio.h}.
3623 @pindex stdio.h
3625 @comment stdio.h
3626 @comment ISO
3627 @deftypefun int fflush (FILE *@var{stream})
3628 This function causes any buffered output on @var{stream} to be delivered
3629 to the file.  If @var{stream} is a null pointer, then
3630 @code{fflush} causes buffered output on @emph{all} open output streams
3631 to be flushed.
3633 This function returns @code{EOF} if a write error occurs, or zero
3634 otherwise.
3635 @end deftypefun
3637 @strong{Compatibility Note:} Some brain-damaged operating systems have
3638 been known to be so thoroughly fixated on line-oriented input and output
3639 that flushing a line buffered stream causes a newline to be written!
3640 Fortunately, this ``feature'' seems to be becoming less common.  You do
3641 not need to worry about this in the GNU system.
3644 @node Controlling Buffering
3645 @subsection Controlling Which Kind of Buffering
3647 After opening a stream (but before any other operations have been
3648 performed on it), you can explicitly specify what kind of buffering you
3649 want it to have using the @code{setvbuf} function.
3650 @cindex buffering, controlling
3652 The facilities listed in this section are declared in the header
3653 file @file{stdio.h}.
3654 @pindex stdio.h
3656 @comment stdio.h
3657 @comment ISO
3658 @deftypefun int setvbuf (FILE *@var{stream}, char *@var{buf}, int @var{mode}, size_t @var{size})
3659 This function is used to specify that the stream @var{stream} should
3660 have the buffering mode @var{mode}, which can be either @code{_IOFBF}
3661 (for full buffering), @code{_IOLBF} (for line buffering), or
3662 @code{_IONBF} (for unbuffered input/output).
3664 If you specify a null pointer as the @var{buf} argument, then @code{setvbuf}
3665 allocates a buffer itself using @code{malloc}.  This buffer will be freed
3666 when you close the stream.
3668 Otherwise, @var{buf} should be a character array that can hold at least
3669 @var{size} characters.  You should not free the space for this array as
3670 long as the stream remains open and this array remains its buffer.  You
3671 should usually either allocate it statically, or @code{malloc}
3672 (@pxref{Unconstrained Allocation}) the buffer.  Using an automatic array
3673 is not a good idea unless you close the file before exiting the block
3674 that declares the array.
3676 While the array remains a stream buffer, the stream I/O functions will
3677 use the buffer for their internal purposes.  You shouldn't try to access
3678 the values in the array directly while the stream is using it for
3679 buffering.
3681 The @code{setvbuf} function returns zero on success, or a nonzero value
3682 if the value of @var{mode} is not valid or if the request could not
3683 be honored.
3684 @end deftypefun
3686 @comment stdio.h
3687 @comment ISO
3688 @deftypevr Macro int _IOFBF
3689 The value of this macro is an integer constant expression that can be
3690 used as the @var{mode} argument to the @code{setvbuf} function to
3691 specify that the stream should be fully buffered.
3692 @end deftypevr
3694 @comment stdio.h
3695 @comment ISO
3696 @deftypevr Macro int _IOLBF
3697 The value of this macro is an integer constant expression that can be
3698 used as the @var{mode} argument to the @code{setvbuf} function to
3699 specify that the stream should be line buffered.
3700 @end deftypevr
3702 @comment stdio.h
3703 @comment ISO
3704 @deftypevr Macro int _IONBF
3705 The value of this macro is an integer constant expression that can be
3706 used as the @var{mode} argument to the @code{setvbuf} function to
3707 specify that the stream should be unbuffered.
3708 @end deftypevr
3710 @comment stdio.h
3711 @comment ISO
3712 @deftypevr Macro int BUFSIZ
3713 The value of this macro is an integer constant expression that is good
3714 to use for the @var{size} argument to @code{setvbuf}.  This value is
3715 guaranteed to be at least @code{256}.
3717 The value of @code{BUFSIZ} is chosen on each system so as to make stream
3718 I/O efficient.  So it is a good idea to use @code{BUFSIZ} as the size
3719 for the buffer when you call @code{setvbuf}.
3721 Actually, you can get an even better value to use for the buffer size
3722 by means of the @code{fstat} system call: it is found in the
3723 @code{st_blksize} field of the file attributes.  @xref{Attribute Meanings}.
3725 Sometimes people also use @code{BUFSIZ} as the allocation size of
3726 buffers used for related purposes, such as strings used to receive a
3727 line of input with @code{fgets} (@pxref{Character Input}).  There is no
3728 particular reason to use @code{BUFSIZ} for this instead of any other
3729 integer, except that it might lead to doing I/O in chunks of an
3730 efficient size.
3731 @end deftypevr
3733 @comment stdio.h
3734 @comment ISO
3735 @deftypefun void setbuf (FILE *@var{stream}, char *@var{buf})
3736 If @var{buf} is a null pointer, the effect of this function is
3737 equivalent to calling @code{setvbuf} with a @var{mode} argument of
3738 @code{_IONBF}.  Otherwise, it is equivalent to calling @code{setvbuf}
3739 with @var{buf}, and a @var{mode} of @code{_IOFBF} and a @var{size}
3740 argument of @code{BUFSIZ}.
3742 The @code{setbuf} function is provided for compatibility with old code;
3743 use @code{setvbuf} in all new programs.
3744 @end deftypefun
3746 @comment stdio.h
3747 @comment BSD
3748 @deftypefun void setbuffer (FILE *@var{stream}, char *@var{buf}, size_t @var{size})
3749 If @var{buf} is a null pointer, this function makes @var{stream} unbuffered.
3750 Otherwise, it makes @var{stream} fully buffered using @var{buf} as the
3751 buffer.  The @var{size} argument specifies the length of @var{buf}.
3753 This function is provided for compatibility with old BSD code.  Use
3754 @code{setvbuf} instead.
3755 @end deftypefun
3757 @comment stdio.h
3758 @comment BSD
3759 @deftypefun void setlinebuf (FILE *@var{stream})
3760 This function makes @var{stream} be line buffered, and allocates the
3761 buffer for you.
3763 This function is provided for compatibility with old BSD code.  Use
3764 @code{setvbuf} instead.
3765 @end deftypefun
3767 @node Other Kinds of Streams
3768 @section Other Kinds of Streams
3770 The GNU library provides ways for you to define additional kinds of
3771 streams that do not necessarily correspond to an open file.
3773 One such type of stream takes input from or writes output to a string.
3774 These kinds of streams are used internally to implement the
3775 @code{sprintf} and @code{sscanf} functions.  You can also create such a
3776 stream explicitly, using the functions described in @ref{String Streams}.
3778 More generally, you can define streams that do input/output to arbitrary
3779 objects using functions supplied by your program.  This protocol is
3780 discussed in @ref{Custom Streams}.
3782 @strong{Portability Note:} The facilities described in this section are
3783 specific to GNU.  Other systems or C implementations might or might not
3784 provide equivalent functionality.
3786 @menu
3787 * String Streams::              Streams that get data from or put data in
3788                                  a string or memory buffer.
3789 * Obstack Streams::             Streams that store data in an obstack.
3790 * Custom Streams::              Defining your own streams with an arbitrary
3791                                  input data source and/or output data sink.
3792 @end menu
3794 @node String Streams
3795 @subsection String Streams
3797 @cindex stream, for I/O to a string
3798 @cindex string stream
3799 The @code{fmemopen} and @code{open_memstream} functions allow you to do
3800 I/O to a string or memory buffer.  These facilities are declared in
3801 @file{stdio.h}.
3802 @pindex stdio.h
3804 @comment stdio.h
3805 @comment GNU
3806 @deftypefun {FILE *} fmemopen (void *@var{buf}, size_t @var{size}, const char *@var{opentype})
3807 This function opens a stream that allows the access specified by the
3808 @var{opentype} argument, that reads from or writes to the buffer specified
3809 by the argument @var{buf}.  This array must be at least @var{size} bytes long.
3811 If you specify a null pointer as the @var{buf} argument, @code{fmemopen}
3812 dynamically allocates an array @var{size} bytes long (as with @code{malloc};
3813 @pxref{Unconstrained Allocation}).  This is really only useful
3814 if you are going to write things to the buffer and then read them back
3815 in again, because you have no way of actually getting a pointer to the
3816 buffer (for this, try @code{open_memstream}, below).  The buffer is
3817 freed when the stream is open.
3819 The argument @var{opentype} is the same as in @code{fopen}
3820 (@pxref{Opening Streams}).  If the @var{opentype} specifies
3821 append mode, then the initial file position is set to the first null
3822 character in the buffer.  Otherwise the initial file position is at the
3823 beginning of the buffer.
3825 When a stream open for writing is flushed or closed, a null character
3826 (zero byte) is written at the end of the buffer if it fits.  You
3827 should add an extra byte to the @var{size} argument to account for this.
3828 Attempts to write more than @var{size} bytes to the buffer result
3829 in an error.
3831 For a stream open for reading, null characters (zero bytes) in the
3832 buffer do not count as ``end of file''.  Read operations indicate end of
3833 file only when the file position advances past @var{size} bytes.  So, if
3834 you want to read characters from a null-terminated string, you should
3835 supply the length of the string as the @var{size} argument.
3836 @end deftypefun
3838 Here is an example of using @code{fmemopen} to create a stream for
3839 reading from a string:
3841 @smallexample
3842 @include memopen.c.texi
3843 @end smallexample
3845 This program produces the following output:
3847 @smallexample
3848 Got f
3849 Got o
3850 Got o
3851 Got b
3852 Got a
3853 Got r
3854 @end smallexample
3856 @comment stdio.h
3857 @comment GNU
3858 @deftypefun {FILE *} open_memstream (char **@var{ptr}, size_t *@var{sizeloc})
3859 This function opens a stream for writing to a buffer.  The buffer is
3860 allocated dynamically (as with @code{malloc}; @pxref{Unconstrained
3861 Allocation}) and grown as necessary.
3863 When the stream is closed with @code{fclose} or flushed with
3864 @code{fflush}, the locations @var{ptr} and @var{sizeloc} are updated to
3865 contain the pointer to the buffer and its size.  The values thus stored
3866 remain valid only as long as no further output on the stream takes
3867 place.  If you do more output, you must flush the stream again to store
3868 new values before you use them again.
3870 A null character is written at the end of the buffer.  This null character
3871 is @emph{not} included in the size value stored at @var{sizeloc}.
3873 You can move the stream's file position with @code{fseek} or
3874 @code{fseeko} (@pxref{File Positioning}).  Moving the file position past
3875 the end of the data already written fills the intervening space with
3876 zeroes.
3877 @end deftypefun
3879 Here is an example of using @code{open_memstream}:
3881 @smallexample
3882 @include memstrm.c.texi
3883 @end smallexample
3885 This program produces the following output:
3887 @smallexample
3888 buf = `hello', size = 5
3889 buf = `hello, world', size = 12
3890 @end smallexample
3892 @c @group  Invalid outside @example.
3893 @node Obstack Streams
3894 @subsection Obstack Streams
3896 You can open an output stream that puts it data in an obstack.
3897 @xref{Obstacks}.
3899 @comment stdio.h
3900 @comment GNU
3901 @deftypefun {FILE *} open_obstack_stream (struct obstack *@var{obstack})
3902 This function opens a stream for writing data into the obstack @var{obstack}.
3903 This starts an object in the obstack and makes it grow as data is
3904 written (@pxref{Growing Objects}).
3905 @c @end group  Doubly invalid because not nested right.
3907 Calling @code{fflush} on this stream updates the current size of the
3908 object to match the amount of data that has been written.  After a call
3909 to @code{fflush}, you can examine the object temporarily.
3911 You can move the file position of an obstack stream with @code{fseek} or
3912 @code{fseeko} (@pxref{File Positioning}).  Moving the file position past
3913 the end of the data written fills the intervening space with zeros.
3915 To make the object permanent, update the obstack with @code{fflush}, and
3916 then use @code{obstack_finish} to finalize the object and get its address.
3917 The following write to the stream starts a new object in the obstack,
3918 and later writes add to that object until you do another @code{fflush}
3919 and @code{obstack_finish}.
3921 But how do you find out how long the object is?  You can get the length
3922 in bytes by calling @code{obstack_object_size} (@pxref{Status of an
3923 Obstack}), or you can null-terminate the object like this:
3925 @smallexample
3926 obstack_1grow (@var{obstack}, 0);
3927 @end smallexample
3929 Whichever one you do, you must do it @emph{before} calling
3930 @code{obstack_finish}.  (You can do both if you wish.)
3931 @end deftypefun
3933 Here is a sample function that uses @code{open_obstack_stream}:
3935 @smallexample
3936 char *
3937 make_message_string (const char *a, int b)
3939   FILE *stream = open_obstack_stream (&message_obstack);
3940   output_task (stream);
3941   fprintf (stream, ": ");
3942   fprintf (stream, a, b);
3943   fprintf (stream, "\n");
3944   fclose (stream);
3945   obstack_1grow (&message_obstack, 0);
3946   return obstack_finish (&message_obstack);
3948 @end smallexample
3950 @node Custom Streams
3951 @subsection Programming Your Own Custom Streams
3952 @cindex custom streams
3953 @cindex programming your own streams
3955 This section describes how you can make a stream that gets input from an
3956 arbitrary data source or writes output to an arbitrary data sink
3957 programmed by you.  We call these @dfn{custom streams}.  The functions
3958 and types described here are all GNU extensions.
3960 @c !!! this does not talk at all about the higher-level hooks
3962 @menu
3963 * Streams and Cookies::         The @dfn{cookie} records where to fetch or
3964                                  store data that is read or written.
3965 * Hook Functions::              How you should define the four @dfn{hook
3966                                  functions} that a custom stream needs.
3967 @end menu
3969 @node Streams and Cookies
3970 @subsubsection Custom Streams and Cookies
3971 @cindex cookie, for custom stream
3973 Inside every custom stream is a special object called the @dfn{cookie}.
3974 This is an object supplied by you which records where to fetch or store
3975 the data read or written.  It is up to you to define a data type to use
3976 for the cookie.  The stream functions in the library never refer
3977 directly to its contents, and they don't even know what the type is;
3978 they record its address with type @code{void *}.
3980 To implement a custom stream, you must specify @emph{how} to fetch or
3981 store the data in the specified place.  You do this by defining
3982 @dfn{hook functions} to read, write, change ``file position'', and close
3983 the stream.  All four of these functions will be passed the stream's
3984 cookie so they can tell where to fetch or store the data.  The library
3985 functions don't know what's inside the cookie, but your functions will
3986 know.
3988 When you create a custom stream, you must specify the cookie pointer,
3989 and also the four hook functions stored in a structure of type
3990 @code{cookie_io_functions_t}.
3992 These facilities are declared in @file{stdio.h}.
3993 @pindex stdio.h
3995 @comment stdio.h
3996 @comment GNU
3997 @deftp {Data Type} {cookie_io_functions_t}
3998 This is a structure type that holds the functions that define the
3999 communications protocol between the stream and its cookie.  It has
4000 the following members:
4002 @table @code
4003 @item cookie_read_function_t *read
4004 This is the function that reads data from the cookie.  If the value is a
4005 null pointer instead of a function, then read operations on this stream
4006 always return @code{EOF}.
4008 @item cookie_write_function_t *write
4009 This is the function that writes data to the cookie.  If the value is a
4010 null pointer instead of a function, then data written to the stream is
4011 discarded.
4013 @item cookie_seek_function_t *seek
4014 This is the function that performs the equivalent of file positioning on
4015 the cookie.  If the value is a null pointer instead of a function, calls
4016 to @code{fseek} or @code{fseeko} on this stream can only seek to
4017 locations within the buffer; any attempt to seek outside the buffer will
4018 return an @code{ESPIPE} error.
4020 @item cookie_close_function_t *close
4021 This function performs any appropriate cleanup on the cookie when
4022 closing the stream.  If the value is a null pointer instead of a
4023 function, nothing special is done to close the cookie when the stream is
4024 closed.
4025 @end table
4026 @end deftp
4028 @comment stdio.h
4029 @comment GNU
4030 @deftypefun {FILE *} fopencookie (void *@var{cookie}, const char *@var{opentype}, cookie_io_functions_t @var{io-functions})
4031 This function actually creates the stream for communicating with the
4032 @var{cookie} using the functions in the @var{io-functions} argument.
4033 The @var{opentype} argument is interpreted as for @code{fopen};
4034 see @ref{Opening Streams}.  (But note that the ``truncate on
4035 open'' option is ignored.)  The new stream is fully buffered.
4037 The @code{fopencookie} function returns the newly created stream, or a null
4038 pointer in case of an error.
4039 @end deftypefun
4041 @node Hook Functions
4042 @subsubsection Custom Stream Hook Functions
4043 @cindex hook functions (of custom streams)
4045 Here are more details on how you should define the four hook functions
4046 that a custom stream needs.
4048 You should define the function to read data from the cookie as:
4050 @smallexample
4051 ssize_t @var{reader} (void *@var{cookie}, char *@var{buffer}, size_t @var{size})
4052 @end smallexample
4054 This is very similar to the @code{read} function; see @ref{I/O
4055 Primitives}.  Your function should transfer up to @var{size} bytes into
4056 the @var{buffer}, and return the number of bytes read, or zero to
4057 indicate end-of-file.  You can return a value of @code{-1} to indicate
4058 an error.
4060 You should define the function to write data to the cookie as:
4062 @smallexample
4063 ssize_t @var{writer} (void *@var{cookie}, const char *@var{buffer}, size_t @var{size})
4064 @end smallexample
4066 This is very similar to the @code{write} function; see @ref{I/O
4067 Primitives}.  Your function should transfer up to @var{size} bytes from
4068 the buffer, and return the number of bytes written.  You can return a
4069 value of @code{-1} to indicate an error.
4071 You should define the function to perform seek operations on the cookie
4074 @smallexample
4075 int @var{seeker} (void *@var{cookie}, fpos_t *@var{position}, int @var{whence})
4076 @end smallexample
4078 For this function, the @var{position} and @var{whence} arguments are
4079 interpreted as for @code{fgetpos}; see @ref{Portable Positioning}.  In
4080 the GNU library, @code{fpos_t} is equivalent to @code{off_t} or
4081 @code{long int}, and simply represents the number of bytes from the
4082 beginning of the file.
4084 After doing the seek operation, your function should store the resulting
4085 file position relative to the beginning of the file in @var{position}.
4086 Your function should return a value of @code{0} on success and @code{-1}
4087 to indicate an error.
4089 You should define the function to do cleanup operations on the cookie
4090 appropriate for closing the stream as:
4092 @smallexample
4093 int @var{cleaner} (void *@var{cookie})
4094 @end smallexample
4096 Your function should return @code{-1} to indicate an error, and @code{0}
4097 otherwise.
4099 @comment stdio.h
4100 @comment GNU
4101 @deftp {Data Type} cookie_read_function
4102 This is the data type that the read function for a custom stream should have.
4103 If you declare the function as shown above, this is the type it will have.
4104 @end deftp
4106 @comment stdio.h
4107 @comment GNU
4108 @deftp {Data Type} cookie_write_function
4109 The data type of the write function for a custom stream.
4110 @end deftp
4112 @comment stdio.h
4113 @comment GNU
4114 @deftp {Data Type} cookie_seek_function
4115 The data type of the seek function for a custom stream.
4116 @end deftp
4118 @comment stdio.h
4119 @comment GNU
4120 @deftp {Data Type} cookie_close_function
4121 The data type of the close function for a custom stream.
4122 @end deftp
4124 @ignore
4125 Roland says:
4127 @quotation
4128 There is another set of functions one can give a stream, the
4129 input-room and output-room functions.  These functions must
4130 understand stdio internals.  To describe how to use these
4131 functions, you also need to document lots of how stdio works
4132 internally (which isn't relevant for other uses of stdio).
4133 Perhaps I can write an interface spec from which you can write
4134 good documentation.  But it's pretty complex and deals with lots
4135 of nitty-gritty details.  I think it might be better to let this
4136 wait until the rest of the manual is more done and polished.
4137 @end quotation
4138 @end ignore
4140 @c ??? This section could use an example.
4143 @node Formatted Messages
4144 @section Formatted Messages
4145 @cindex formatted messages
4147 On systems which are based on System V messages of programs (especially
4148 the system tools) are printed in a strict form using the @code{fmtmsg}
4149 function.  The uniformity sometimes helps the user to interpret messages
4150 and the strictness tests of the @code{fmtmsg} function ensure that the
4151 programmer follows some minimal requirements.
4153 @menu
4154 * Printing Formatted Messages::   The @code{fmtmsg} function.
4155 * Adding Severity Classes::       Add more severity classes.
4156 * Example::                       How to use @code{fmtmsg} and @code{addseverity}.
4157 @end menu
4160 @node Printing Formatted Messages
4161 @subsection Printing Formatted Messages
4163 Messages can be printed to standard error and/or to the console.  To
4164 select the destination the programmer can use the following two values,
4165 bitwise OR combined if wanted, for the @var{classification} parameter of
4166 @code{fmtmsg}:
4168 @vtable @code
4169 @item MM_PRINT
4170 Display the message in standard error.
4171 @item MM_CONSOLE
4172 Display the message on the system console.
4173 @end vtable
4175 The erroneous piece of the system can be signalled by exactly one of the
4176 following values which also is bitwise ORed with the
4177 @var{classification} parameter to @code{fmtmsg}:
4179 @vtable @code
4180 @item MM_HARD
4181 The source of the condition is some hardware.
4182 @item MM_SOFT
4183 The source of the condition is some software.
4184 @item MM_FIRM
4185 The source of the condition is some firmware.
4186 @end vtable
4188 A third component of the @var{classification} parameter to @code{fmtmsg}
4189 can describe the part of the system which detects the problem.  This is
4190 done by using exactly one of the following values:
4192 @vtable @code
4193 @item MM_APPL
4194 The erroneous condition is detected by the application.
4195 @item MM_UTIL
4196 The erroneous condition is detected by a utility.
4197 @item MM_OPSYS
4198 The erroneous condition is detected by the operating system.
4199 @end vtable
4201 A last component of @var{classification} can signal the results of this
4202 message.  Exactly one of the following values can be used:
4204 @vtable @code
4205 @item MM_RECOVER
4206 It is a recoverable error.
4207 @item MM_NRECOV
4208 It is a non-recoverable error.
4209 @end vtable
4211 @comment fmtmsg.h
4212 @comment XPG
4213 @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})
4214 Display a message described by its parameters on the device(s) specified
4215 in the @var{classification} parameter.  The @var{label} parameter
4216 identifies the source of the message.  The string should consist of two
4217 colon separated parts where the first part has not more than 10 and the
4218 second part not more than 14 characters.  The @var{text} parameter
4219 describes the condition of the error, the @var{action} parameter possible
4220 steps to recover from the error and the @var{tag} parameter is a
4221 reference to the online documentation where more information can be
4222 found.  It should contain the @var{label} value and a unique
4223 identification number.
4225 Each of the parameters can be a special value which means this value
4226 is to be omitted.  The symbolic names for these values are:
4228 @vtable @code
4229 @item MM_NULLLBL
4230 Ignore @var{label} parameter.
4231 @item MM_NULLSEV
4232 Ignore @var{severity} parameter.
4233 @item MM_NULLMC
4234 Ignore @var{classification} parameter.  This implies that nothing is
4235 actually printed.
4236 @item MM_NULLTXT
4237 Ignore @var{text} parameter.
4238 @item MM_NULLACT
4239 Ignore @var{action} parameter.
4240 @item MM_NULLTAG
4241 Ignore @var{tag} parameter.
4242 @end vtable
4244 There is another way certain fields can be omitted from the output to
4245 standard error.  This is described below in the description of
4246 environment variables influencing the behaviour.
4248 The @var{severity} parameter can have one of the values in the following
4249 table:
4250 @cindex severity class
4252 @vtable @code
4253 @item MM_NOSEV
4254 Nothing is printed, this value is the same as @code{MM_NULLSEV}.
4255 @item MM_HALT
4256 This value is printed as @code{HALT}.
4257 @item MM_ERROR
4258 This value is printed as @code{ERROR}.
4259 @item MM_WARNING
4260 This value is printed as @code{WARNING}.
4261 @item MM_INFO
4262 This value is printed as @code{INFO}.
4263 @end vtable
4265 The numeric value of these five macros are between @code{0} and
4266 @code{4}.  Using the environment variable @code{SEV_LEVEL} or using the
4267 @code{addseverity} function one can add more severity levels with their
4268 corresponding string to print.  This is described below
4269 (@pxref{Adding Severity Classes}).
4271 @noindent
4272 If no parameter is ignored the output looks like this:
4274 @smallexample
4275 @var{label}: @var{severity-string}: @var{text}
4276 TO FIX: @var{action} @var{tag}
4277 @end smallexample
4279 The colons, new line characters and the @code{TO FIX} string are
4280 inserted if necessary, i.e., if the corresponding parameter is not
4281 ignored.
4283 This function is specified in the X/Open Portability Guide.  It is also
4284 available on all systems derived from System V.
4286 The function returns the value @code{MM_OK} if no error occurred.  If
4287 only the printing to standard error failed, it returns @code{MM_NOMSG}.
4288 If printing to the console fails, it returns @code{MM_NOCON}.  If
4289 nothing is printed @code{MM_NOTOK} is returned.  Among situations where
4290 all outputs fail this last value is also returned if a parameter value
4291 is incorrect.
4292 @end deftypefun
4294 There are two environment variables which influence the behaviour of
4295 @code{fmtmsg}.  The first is @code{MSGVERB}.  It is used to control the
4296 output actually happening on standard error (@emph{not} the console
4297 output).  Each of the five fields can explicitly be enabled.  To do
4298 this the user has to put the @code{MSGVERB} variable with a format like
4299 the following in the environment before calling the @code{fmtmsg} function
4300 the first time:
4302 @smallexample
4303 MSGVERB=@var{keyword}[:@var{keyword}[:...]]
4304 @end smallexample
4306 Valid @var{keyword}s are @code{label}, @code{severity}, @code{text},
4307 @code{action}, and @code{tag}.  If the environment variable is not given
4308 or is the empty string, a not supported keyword is given or the value is
4309 somehow else invalid, no part of the message is masked out.
4311 The second environment variable which influences the behaviour of
4312 @code{fmtmsg} is @code{SEV_LEVEL}.  This variable and the change in the
4313 behaviour of @code{fmtmsg} is not specified in the X/Open Portability
4314 Guide.  It is available in System V systems, though.  It can be used to
4315 introduce new severity levels.  By default, only the five severity levels
4316 described above are available.  Any other numeric value would make
4317 @code{fmtmsg} print nothing.
4319 If the user puts @code{SEV_LEVEL} with a format like
4321 @smallexample
4322 SEV_LEVEL=[@var{description}[:@var{description}[:...]]]
4323 @end smallexample
4325 @noindent
4326 in the environment of the process before the first call to
4327 @code{fmtmsg}, where @var{description} has a value of the form
4329 @smallexample
4330 @var{severity-keyword},@var{level},@var{printstring}
4331 @end smallexample
4333 The @var{severity-keyword} part is not used by @code{fmtmsg} but it has
4334 to be present.  The @var{level} part is a string representation of a
4335 number.  The numeric value must be a number greater than 4.  This value
4336 must be used in the @var{severity} parameter of @code{fmtmsg} to select
4337 this class.  It is not possible to overwrite any of the predefined
4338 classes.  The @var{printstring} is the string printed when a message of
4339 this class is processed by @code{fmtmsg} (see above, @code{fmtsmg} does
4340 not print the numeric value but instead the string representation).
4343 @node Adding Severity Classes
4344 @subsection Adding Severity Classes
4345 @cindex severity class
4347 There is another possibility to introduce severity classes besides using
4348 the environment variable @code{SEV_LEVEL}.  This simplifies the task of
4349 introducing new classes in a running program.  One could use the
4350 @code{setenv} or @code{putenv} function to set the environment variable,
4351 but this is toilsome.
4353 @deftypefun int addseverity (int @var{severity}, const char *@var{string})
4354 This function allows the introduction of new severity classes which can be
4355 addressed by the @var{severity} parameter of the @code{fmtmsg} function.
4356 The @var{severity} parameter of @code{addseverity} must match the value
4357 for the parameter with the same name of @code{fmtmsg}, and @var{string}
4358 is the string printed in the actual messages instead of the numeric
4359 value.
4361 If @var{string} is @code{NULL} the severity class with the numeric value
4362 according to @var{severity} is removed.
4364 It is not possible to overwrite or remove one of the default severity
4365 classes.  All calls to @code{addseverity} with @var{severity} set to one
4366 of the values for the default classes will fail.
4368 The return value is @code{MM_OK} if the task was successfully performed.
4369 If the return value is @code{MM_NOTOK} something went wrong.  This could
4370 mean that no more memory is available or a class is not available when
4371 it has to be removed.
4373 This function is not specified in the X/Open Portability Guide although
4374 the @code{fmtsmg} function is.  It is available on System V systems.
4375 @end deftypefun
4378 @node Example
4379 @subsection How to use @code{fmtmsg} and @code{addseverity}
4381 Here is a simple example program to illustrate the use of the both
4382 functions described in this section.
4384 @smallexample
4385 @include fmtmsgexpl.c.texi
4386 @end smallexample
4388 The second call to @code{fmtmsg} illustrates a use of this function as
4389 it usually occurs on System V systems, which heavily use this function.
4390 It seems worthwhile to give a short explanation here of how this system
4391 works on System V.  The value of the
4392 @var{label} field (@code{UX:cat}) says that the error occured in the
4393 Unix program @code{cat}.  The explanation of the error follows and the
4394 value for the @var{action} parameter is @code{"refer to manual"}.  One
4395 could be more specific here, if necessary.  The @var{tag} field contains,
4396 as proposed above, the value of the string given for the @var{label}
4397 parameter, and additionally a unique ID (@code{001} in this case).  For
4398 a GNU environment this string could contain a reference to the
4399 corresponding node in the Info page for the program.
4401 @noindent
4402 Running this program without specifying the @code{MSGVERB} and
4403 @code{SEV_LEVEL} function produces the following output:
4405 @smallexample
4406 UX:cat: NOTE2: invalid syntax
4407 TO FIX: refer to manual UX:cat:001
4408 @end smallexample
4410 We see the different fields of the message and how the extra glue (the
4411 colons and the @code{TO FIX} string) are printed.  But only one of the
4412 three calls to @code{fmtmsg} produced output.  The first call does not
4413 print anything because the @var{label} parameter is not in the correct
4414 form.  The string must contain two fields, separated by a colon
4415 (@pxref{Printing Formatted Messages}).  The third @code{fmtmsg} call
4416 produced no output since the class with the numeric value @code{6} is
4417 not defined.  Although a class with numeric value @code{5} is also not
4418 defined by default, the call to @code{addseverity} introduces it and
4419 the second call to @code{fmtmsg} produces the above output.
4421 When we change the environment of the program to contain
4422 @code{SEV_LEVEL=XXX,6,NOTE} when running it we get a different result:
4424 @smallexample
4425 UX:cat: NOTE2: invalid syntax
4426 TO FIX: refer to manual UX:cat:001
4427 label:foo: NOTE: text
4428 TO FIX: action tag
4429 @end smallexample
4431 Now the third call to @code{fmtmsg} produced some output and we see how
4432 the string @code{NOTE} from the environment variable appears in the
4433 message.
4435 Now we can reduce the output by specifying which fields we are
4436 interested in.  If we additionally set the environment variable
4437 @code{MSGVERB} to the value @code{severity:label:action} we get the
4438 following output:
4440 @smallexample
4441 UX:cat: NOTE2
4442 TO FIX: refer to manual
4443 label:foo: NOTE
4444 TO FIX: action
4445 @end smallexample
4447 @noindent
4448 I.e., the output produced by the @var{text} and the @var{tag} parameters
4449 to @code{fmtmsg} vanished.  Please also note that now there is no colon
4450 after the @code{NOTE} and @code{NOTE2} strings in the output.  This is
4451 not necessary since there is no more output on this line because the text
4452 is missing.