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