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