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