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