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