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