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