1 \input texinfo @c -*-Texinfo-*-
2 @c Copyright (c) 1993 Free Software Foundation, Inc.
5 @setfilename iostream.info
6 @settitle The GNU C++ Iostream Library
13 * iostream: (iostream). The C++ input/output facility.
17 This file describes libio, the GNU library for C++ iostreams and C stdio.
19 libio includes software developed by the University of California,
22 Copyright (C) 1993 Free Software Foundation, Inc.
24 Permission is granted to make and distribute verbatim copies of
25 this manual provided the copyright notice and this permission notice
26 are preserved on all copies.
29 Permission is granted to process this file through TeX and print the
30 results, provided the printed document carries copying permission
31 notice identical to this one except for the removal of this paragraph
32 (this paragraph not being relevant to the printed manual).
35 Permission is granted to copy and distribute modified versions of this
36 manual under the conditions for verbatim copying, provided also that the
37 entire resulting derived work is distributed under the terms of a
38 permission notice identical to this one.
40 Permission is granted to copy and distribute translations of this manual
41 into another language, under the above conditions for modified versions.
49 @title The GNU C++ Iostream Library
50 @subtitle Reference Manual for @code{libio} Version 0.64
52 @author Per Bothner @hfill @code{bothner@@cygnus.com}
53 @author Cygnus Support @hfill @code{doc@@cygnus.com}
56 @vskip 0pt plus 1filll
57 Copyright @copyright{} 1993 Free Software Foundation, Inc.
59 @code{libio} includes software developed by the University of
62 @code{libio} uses floating-point software written by David M. Gay, which
63 includes the following notice:
66 The author of this software is David M. Gay.
68 Copyright (c) 1991 by AT&T.
70 Permission to use, copy, modify, and distribute this software for any
71 purpose without fee is hereby granted, provided that this entire notice
72 is included in all copies of any software which is or includes a copy
73 or modification of this software and in all copies of the supporting
74 documentation for such software.
76 THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
77 WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR AT&T MAKES ANY
78 REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
79 OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
82 Permission is granted to make and distribute verbatim copies of
83 this manual provided the copyright notice and this permission notice
84 are preserved on all copies.
86 Permission is granted to copy and distribute modified versions of this
87 manual under the conditions for verbatim copying, provided also that the
88 entire resulting derived work is distributed under the terms of a
89 permission notice identical to this one.
91 Permission is granted to copy and distribute translations of this manual
92 into another language, under the above conditions for modified versions.
97 @top The GNU C++ Iostream Library
99 This file provides reference information on the GNU C++ iostream library
100 (@code{libio}), version 0.64.
104 * Operators:: Operators and default streams.
105 * Streams:: Stream classes.
106 * Files and Strings:: Classes for files and strings.
107 * Streambuf:: Using the streambuf layer.
108 * Stdio:: C input and output.
114 @chapter Introduction
116 The iostream classes implement most of the features of AT&T version 2.0
117 iostream library classes, and most of the features of the ANSI X3J16
118 library draft (which is based on the AT&T design).
120 This manual is meant as a reference; for tutorial material on iostreams,
121 see the corresponding section of any recent popular introduction to C++.
124 * Copying:: Special GNU licensing terms for libio.
125 * Acknowledgements:: Contributors to GNU iostream.
129 @section Licensing terms for @code{libio}
131 Since the @code{iostream} classes are so fundamental to standard C++,
132 the Free Software Foundation has agreed to a special exception to its
133 standard license, when you link programs with @code{libio.a}:
136 As a special exception, if you link this library with files
137 compiled with a GNU compiler to produce an executable, this does not cause
138 the resulting executable to be covered by the GNU General Public License.
139 This exception does not however invalidate any other reasons why
140 the executable file might be covered by the GNU General Public License.
143 The code is under the @sc{gnu} General Public License (version 2) for
144 all other purposes than linking with this library; that means that you
145 can modify and redistribute the code as usual, but remember that if you
146 do, your modifications, and anything you link with the modified code,
147 must be available to others on the same terms.
149 These functions are also available as part of the @code{libg++}
150 library; if you link with that library instead of @code{libio}, the
151 @sc{gnu} Library General Public License applies.
153 @node Acknowledgements
154 @section Acknowledgements
156 Per Bothner wrote most of the @code{iostream} library, but some portions
157 have their origins elsewhere in the free software community. Heinz
158 Seidl wrote the IO manipulators. The floating-point conversion software
159 is by David M. Gay of AT&T. Some code was derived from parts of BSD
160 4.4, which was written at the University of California, Berkeley.
162 The iostream classes are found in the @code{libio} library. An early
163 version was originally distributed in @code{libg++}, and they are still
164 included there as well, for convenience if you need other @code{libg++}
165 classes. Doug Lea was the original author of @code{libg++}, and some of
166 the file-management code still in @code{libio} is his.
168 Various people found bugs or offered suggestions. Hongjiu Lu worked
169 hard to use the library as the default stdio implementation for Linux,
170 and has provided much stress-testing of the library.
173 @chapter Operators and Default Streams
175 The @sc{gnu} iostream library, @file{libio}, implements the standard
176 input and output facilities for C++. These facilities are roughly
177 analogous (in their purpose and ubiquity, at least) with those defined
178 by the C @file{stdio} functions.
180 Although these definitions come from a library, rather than being part
181 of the ``core language'', they are sufficiently central to be specified
182 in the latest working papers for C++.
184 You can use two operators defined in this library for basic input and
185 output operations. They are familiar from any C++ introductory
186 textbook: @code{<<} for output, and @code{>>} for input. (Think of data
187 flowing in the direction of the ``arrows''.)
189 These operators are often used in conjunction with three streams that
192 @deftypevar ostream cout
193 The standard output stream, analogous to the C @code{stdout}.
196 @deftypevar istream cin
197 The standard input stream, analogous to the C @code{stdin}.
200 @deftypevar ostream cerr
201 An alternative output stream for errors, analogous to the C
206 For example, this bare-bones C++ version of the traditional ``hello''
207 program uses @code{<<} and @code{cout}:
210 #include <iostream.h>
212 int main(int argc, char **argv)
214 cout << "Well, hi there.\n";
219 Casual use of these operators may be seductive, but---other than in
220 writing throwaway code for your own use---it is not necessarily simpler
221 than managing input and output in any other language. For example,
222 robust code should check the state of the input and output streams
223 between operations (for example, using the method @code{good}).
224 @xref{States,,Checking the state of a stream}. You may also need to
225 adjust maximum input or output field widths, using manipulators like
226 @code{setw} or @code{setprecision}.
228 @defop Operator ostream <<
229 Write output to an open output stream of class @code{ostream}.
230 Defined by this library on any @var{object} of a C++ primitive type, and
231 on other classes of the library. You can overload the definition for any
232 of your own applications' classes.
234 Returns a reference to the implied argument @code{*this} (the open stream it
235 writes on), permitting statements like
237 cout << "The value of i is " << i << "\n";
241 @defop Operator istream >>
242 Read input from an open input stream of class @code{istream}. Defined
243 by this library on primitive numeric, pointer, and string types; you can
244 extend the definition for any of your own applications' classes.
246 Returns a reference to the implied argument @code{*this} (the open stream
247 it reads), permitting multiple inputs in one statement.
251 @chapter Stream Classes
253 The previous chapter referred in passing to the classes @code{ostream}
254 and @code{istream}, for output and input respectively. These classes
255 share certain properties, captured in their base class @code{ios}.
258 * Ios:: Shared properties.
259 * Ostream:: Managing output streams.
260 * Istream:: Managing input streams.
261 * Iostream:: Input and output together.
265 @section Shared properties: class @code{ios}
267 The base class @code{ios} provides methods to test and manage the state
268 of input or output streams.
270 @code{ios} delegates the job of actually reading and writing bytes to
271 the abstract class @code{streambuf}, which is designed to provide
272 buffered streams (compatible with C, in the @sc{gnu} implementation).
273 @xref{Streambuf,,Using the @code{streambuf} layer}, for information on
274 the facilities available at the @code{streambuf} level.
276 @deftypefn Constructor {} ios::ios ([streambuf* @var{sb} @w{[, ostream*} @var{tie}])
277 The @code{ios} constructor by default initializes a new @code{ios}, and
278 if you supply a @code{streambuf} @var{sb} to associate with it, sets the
279 state @code{good} in the new @code{ios} object. It also sets the
280 default properties of the new object.
283 @c FIXME--future: this (a) doesn't work, (b) is controversial at ANSI
284 An @code{ios} without a @code{streambuf} has the state @code{bad} until
285 you supply a @code{streambuf}; you can do that by assigning a new value
286 to the @code{ios} with @samp{=}.
289 You can also supply an optional second argument @var{tie} to the
290 constructor: if present, it is an initial value for @code{ios::tie}, to
291 associate the new @code{ios} object with another stream.
294 @deftypefn Destructor {} ios::~ios ()
295 The @code{ios} destructor is virtual, permitting application-specific
296 behavior when a stream is closed---typically, the destructor frees any
297 storage associated with the stream and releases any other associated
301 @c FIXME-future: Is @deftypefn really the best way of displaying these?
303 @c FIXME-future: Undocumented: ios::_throw_failure, ios::exceptions; things
304 @c controlled by _STREAM_COMPAT; ios::Init; ios::_IO_fix_vtable.
307 * States:: Checking the state of a stream.
308 * Format Control:: Choices in formatting.
309 * Manipulators:: Convenient ways of changing stream properties.
310 * Extending:: Extended data fields.
311 * Synchronization:: Synchronizing related streams.
312 * Streambuf from Ios:: Reaching the underlying streambuf.
316 @subsection Checking the state of a stream
318 Use this collection of methods to test for (or signal) errors and other
319 exceptional conditions of streams:
321 @deftypefn Method {ios::operator void*} () const
322 You can do a quick check on the state of the most recent operation on a
323 stream by examining a pointer to the stream itself. The pointer is
324 arbitrary except for its truth value; it is true if no failures have
325 occurred (@code{ios::fail} is not true). For example, you might ask for
326 input on @code{cin} only if all prior output operations succeeded:
331 // Everything OK so far
338 @deftypefn Method {ios::operator !} () const
339 In case it is more convenient to check whether something has failed, the
340 operator @code{!} returns true if @code{ios::fail} is true (an operation
341 has failed). For example,
342 you might issue an error message if input failed:
353 @deftypefn Method iostate ios::rdstate () const
354 Return the state flags for this stream. The value is from the
355 enumeration @code{iostate}. You can test for any combination of
359 There are no indications of exceptional states on this stream.
365 An operation has failed on this stream; this usually indicates bad
369 The stream is unusable.
373 @deftypefn Method void ios::setstate (iostate @var{state})
375 Set the state flag for this stream to @var{state} @emph{in addition to}
376 any state flags already set. Synonym (for upward compatibility):
379 See @code{ios::clear} to set the stream state without regard to existing
380 state flags. See @code{ios::good}, @code{ios::eof}, @code{ios::fail},
381 and @code{ios::bad}, to test the state.
384 @deftypefn Method int ios::good () const
385 Test the state flags associated with this stream; true if no error
389 @deftypefn Method int ios::bad () const
390 Test whether a stream is marked as unusable. (Whether
391 @code{ios::badbit} is set.)
394 @deftypefn Method int ios::eof () const
395 True if end of file was reached on this stream. (If @code{ios::eofbit}
399 @deftypefn Method int ios::fail () const
400 Test for any kind of failure on this stream: @emph{either} some
401 operation failed, @emph{or} the stream is marked as bad. (If either
402 @code{ios::failbit} or @code{ios::badbit} is set.)
405 @deftypefn Method void ios::clear (iostate @var{state})
406 @c FIXME-future: There is some complication to do with buffering and _throw_failure
407 Set the state indication for this stream to the argument @var{state}.
408 You may call @code{ios::clear} with no argument, in which case the state
409 is set to @code{good} (no errors pending).
411 See @code{ios::good}, @code{ios::eof}, @code{ios::fail}, and
412 @code{ios::bad}, to test the state; see @code{ios::set} or
413 @code{ios::setstate} for an alternative way of setting the state.
417 @subsection Choices in formatting
419 These methods control (or report on) settings for some details of
420 controlling streams, primarily to do with formatting output:
422 @deftypefn Method char ios::fill () const
423 Report on the padding character in use.
426 @deftypefn Method char ios::fill (char @var{padding})
427 Set the padding character. You can also use the manipulator
428 @code{setfill}. @xref{Manipulators,,Changing stream properties in
434 @deftypefn Method int ios::precision () const
435 Report the number of significant digits currently in use for output of
436 floating point numbers.
441 @deftypefn Method int ios::precision (int @var{signif})
442 Set the number of significant digits (for input and output numeric
443 conversions) to @var{signif}.
446 @cindex setting @code{ios::precision}
447 You can also use the manipulator @code{setprecision} for this purpose.
448 @xref{Manipulators,,Changing stream properties using manipulators}.
451 @deftypefn Method int ios::width () const
452 Report the current output field width setting (the number of
453 characters to write on the next @samp{<<} output operation).
455 Default: @code{0}, which means to use as many characters as necessary.
458 @deftypefn Method int ios::width (int @var{num})
459 Set the input field width setting to @var{num}. Return the
460 @emph{previous} value for this stream.
463 @cindex setting @code{ios::width}
464 This value resets to zero (the default) every time you use @samp{<<}; it is
465 essentially an additional implicit argument to that operator. You can
466 also use the manipulator @code{setw} for this purpose.
467 @xref{Manipulators,,Changing stream properties using manipulators}.
471 @deftypefn Method fmtflags ios::flags () const
472 Return the current value of the complete collection of flags controlling
473 the format state. These are the flags and their meanings when set:
479 What numeric base to use in converting integers from internal to display
480 representation, or vice versa: decimal, octal, or hexadecimal,
481 respectively. (You can change the base using the manipulator
482 @code{setbase}, or any of the manipulators @code{dec}, @code{oct}, or
483 @code{hex}; @pxref{Manipulators,,Changing stream properties in
486 On input, if none of these flags is set, read numeric constants
487 according to the prefix: decimal if no prefix (or a @samp{.} suffix),
488 octal if a @samp{0} prefix is present, hexadecimal if a @samp{0x} prefix
494 Avoid scientific notation, and always show a fixed number of digits after
495 the decimal point, according to the output precision in effect.
496 Use @code{ios::precision} to set precision.
501 Where output is to appear in a fixed-width field; left-justified,
502 right-justified, or with padding in the middle (e.g. between a numeric
503 sign and the associated value), respectively.
505 @item ios::scientific
506 Use scientific (exponential) notation to display numbers.
509 Display the conventional prefix as a visual indicator of the conversion
510 base: no prefix for decimal, @samp{0} for octal, @samp{0x} for hexadecimal.
513 Display a decimal point and trailing zeros after it to fill out numeric
514 fields, even when redundant.
517 Display a positive sign on display of positive numbers.
520 Skip white space. (On by default).
523 Flush the C @code{stdio} streams @code{stdout} and @code{stderr} after
524 each output operation (for programs that mix C and C++ output conventions).
527 Flush after each output operation.
530 Use upper-case characters for the non-numeral elements in numeric
531 displays; for instance, @samp{0X7A} rather than @samp{0x7a}, or
532 @samp{3.14E+09} rather than @samp{3.14e+09}.
536 @deftypefn Method fmtflags ios::flags (fmtflags @var{value})
537 Set @var{value} as the complete collection of flags controlling the
538 format state. The flag values are described under @samp{ios::flags ()}.
540 Use @code{ios::setf} or @code{ios::unsetf} to change one property at a
544 @deftypefn Method fmtflags ios::setf (fmtflags @var{flag})
545 Set one particular flag (of those described for @samp{ios::flags ()};
546 return the complete collection of flags @emph{previously} in effect.
547 (Use @code{ios::unsetf} to cancel.)
550 @deftypefn Method fmtflags ios::setf (fmtflags @var{flag}, fmtflags @var{mask})
551 Clear the flag values indicated by @var{mask}, then set any of them that
552 are also in @var{flag}. (Flag values are described for @samp{ios::flags
553 ()}.) Return the complete collection of flags @emph{previously} in
554 effect. (See @code{ios::unsetf} for another way of clearing flags.)
557 @deftypefn Method fmtflags ios::unsetf (fmtflags @var{flag})
558 Make certain @var{flag} (a combination of flag values described for
559 @samp{ios::flags ()}) is not set for this stream; converse of
560 @code{ios::setf}. Returns the old values of those flags.
561 @c FIXME-future: should probably be fixed to give same result as setf.
565 @subsection Changing stream properties using manipulators
567 For convenience, @var{manipulators} provide a way to change certain
568 properties of streams, or otherwise affect them, in the middle of
569 expressions involving @samp{<<} or @samp{>>}. For example, you might
573 cout << "|" << setfill('*') << setw(5) << 234 << "|";
577 to produce @samp{|**234|} as output.
579 @deftypefn Manipulator {} ws
583 @deftypefn Manipulator {} flush
584 Flush an output stream. For example, @samp{cout << @dots{} <<flush;}
585 has the same effect as @samp{cout << @dots{}; cout.flush();}.
588 @deftypefn Manipulator {} endl
589 Write an end of line character @samp{\n}, then flushes the output stream.
592 @deftypefn Manipulator {} ends
593 Write @samp{\0} (the string terminator character).
596 @deftypefn Manipulator {} setprecision (int @var{signif})
597 You can change the value of @code{ios::precision} in @samp{<<}
598 expressions with the manipulator @samp{setprecision(@var{signif})}; for
602 cout << setprecision(2) << 4.567;
606 prints @samp{4.6}. Requires @file{#include <iomanip.h>}.
609 @deftypefn Manipulator {} setw (int @var{n})
610 You can change the value of @code{ios::width} in @samp{<<} expressions
611 with the manipulator @samp{setw(@var{n})}; for example,
614 cout << setw(5) << 234;
618 prints @w{@samp{ 234}} with two leading blanks. Requires @file{#include
622 @deftypefn Manipulator {} setbase (int @var{base})
623 Where @var{base} is one of @code{10} (decimal), @code{8} (octal), or
624 @code{16} (hexadecimal), change the base value for numeric
625 representations. Requires @file{#include <iomanip.h>}.
628 @deftypefn Manipulator {} dec
629 Select decimal base; equivalent to @samp{setbase(10)}.
632 @deftypefn Manipulator {} hex
633 Select hexadecimal base; equivalent to @samp{setbase(16)}.
636 @deftypefn Manipulator {} oct
637 Select octal base; equivalent to @samp{setbase(8)}.
640 @deftypefn Manipulator {} setfill (char @var{padding})
641 Set the padding character, in the same way as @code{ios::fill}.
642 Requires @file{#include <iomanip.h>}.
646 @subsection Extended data fields
648 A related collection of methods allows you to extend this collection of
649 flags and parameters for your own applications, without risk of conflict
652 @deftypefn Method {static fmtflags} ios::bitalloc ()
653 Reserve a bit (the single bit on in the result) to use as a flag. Using
654 @code{bitalloc} guards against conflict between two packages that use
655 @code{ios} objects for different purposes.
657 This method is available for upward compatibility, but is not in the
658 @sc{ansi} working paper. The number of bits available is limited; a
659 return value of @code{0} means no bit is available.
662 @deftypefn Method {static int} ios::xalloc ()
663 Reserve space for a long integer or pointer parameter. The result is a
664 unique nonnegative integer. You can use it as an index to
665 @code{ios::iword} or @code{ios::pword}. Use @code{xalloc} to arrange
666 for arbitrary special-purpose data in your @code{ios} objects, without
667 risk of conflict between packages designed for different purposes.
670 @deftypefn Method long& ios::iword (int @var{index})
671 Return a reference to arbitrary data, of long integer type, stored in an
672 @code{ios} instance. @var{index}, conventionally returned from
673 @code{ios::xalloc}, identifies what particular data you need.
676 @deftypefn Method long ios::iword (int @var{index}) const
677 Return the actual value of a long integer stored in an @code{ios}.
680 @deftypefn Method void*& ios::pword (int @var{index})
681 Return a reference to an arbitrary pointer, stored in an @code{ios}
682 instance. @var{index}, originally returned from @code{ios::xalloc},
683 identifies what particular pointer you need.
686 @deftypefn Method void* ios::pword (int @var{index}) const
687 Return the actual value of a pointer stored in an @code{ios}.
690 @node Synchronization
691 @subsection Synchronizing related streams
693 You can use these methods to synchronize related streams with
696 @deftypefn Method ostream* ios::tie () const
697 Report on what output stream, if any, is to be flushed before accessing
698 this one. A pointer value of @code{0} means no stream is tied.
701 @deftypefn Method ostream* ios::tie (ostream* @var{assoc})
702 Declare that output stream @var{assoc} must be flushed before accessing
706 @deftypefn Method int ios::sync_with_stdio ([int @var{switch}])
707 Unless iostreams and C @code{stdio} are designed to work together, you
708 may have to choose between efficient C++ streams output and output
709 compatible with C @code{stdio}. Use @samp{ios::sync_with_stdio()} to
710 select C compatibility.
712 The argument @var{switch} is a @sc{gnu} extension; use @code{0} as the
713 argument to choose output that is not necessarily compatible with C
714 @code{stdio}. The default value for @var{switch} is @code{1}.
716 If you install the @code{stdio} implementation that comes with @sc{gnu}
717 @code{libio}, there are compatible input/output facilities for both C
718 and C++. In that situation, this method is unnecessary---but you may
719 still want to write programs that call it, for portability.
722 @node Streambuf from Ios
723 @subsection Reaching the underlying @code{streambuf}
725 Finally, you can use this method to access the underlying object:
727 @deftypefn Method streambuf* ios::rdbuf () const
728 Return a pointer to the @code{streambuf} object that underlies this
733 @section Managing output streams: class @code{ostream}
735 Objects of class @code{ostream} inherit the generic methods from
736 @code{ios}, and in addition have the following methods available.
737 Declarations for this class come from @file{iostream.h}.
739 @deftypefn Constructor {} ostream::ostream ()
740 The simplest form of the constructor for an @code{ostream} simply
741 allocates a new @code{ios} object.
744 @deftypefn Constructor {} ostream::ostream (streambuf* @var{sb} @w{[, ostream} @var{tie}])
745 This alternative constructor requires a first argument @var{sb} of type
746 @code{streambuf*}, to use an existing open stream for output. It also
747 accepts an optional second argument @var{tie}, to specify a related
748 @code{ostream*} as the initial value for @code{ios::tie}.
750 If you give the @code{ostream} a @code{streambuf} explicitly, using
751 this constructor, the @var{sb} is @emph{not} destroyed (or deleted or
752 closed) when the @code{ostream} is destroyed.
756 * Writing:: Writing on an ostream.
757 * Output Position:: Repositioning an ostream.
758 * Ostream Housekeeping:: Miscellaneous ostream utilities.
762 @subsection Writing on an @code{ostream}
764 These methods write on an @code{ostream} (you may also use the operator
765 @code{<<}; @pxref{Operators,,Operators and Default Streams}).
767 @deftypefn Method ostream& ostream::put (char @var{c})
768 Write the single character @var{c}.
771 @deftypefn Method ostream& ostream::write (@var{string}, int @var{length})
772 Write @var{length} characters of a string to this @code{ostream},
773 beginning at the pointer @var{string}.
775 @var{string} may have any of these types: @code{char*}, @code{unsigned
776 char*}, @code{signed char*}.
779 @deftypefn Method ostream& ostream::form (const char *@var{format}, ...)
780 A @sc{gnu} extension, similar to @code{fprintf(@var{file},
783 @var{format} is a @code{printf}-style format control string, which is used
784 to format the (variable number of) arguments, printing the result on
785 this @code{ostream}. See @code{ostream::vform} for a version that uses
786 an argument list rather than a variable number of arguments.
789 @deftypefn Method ostream& ostream::vform (const char *@var{format}, va_list @var{args})
790 A @sc{gnu} extension, similar to @code{vfprintf(@var{file},
791 @var{format}, @var{args})}.
793 @var{format} is a @code{printf}-style format control string, which is used
794 to format the argument list @var{args}, printing the result on
795 this @code{ostream}. See @code{ostream::form} for a version that uses a
796 variable number of arguments rather than an argument list.
799 @node Output Position
800 @subsection Repositioning an @code{ostream}
802 You can control the output position (on output streams that actually
803 support positions, typically files) with these methods:
804 @c FIXME-future: sort out which classes support this and which
805 @c don't; fstream, filebuf? And what is failure condition when not supported?
807 @deftypefn Method streampos ostream::tellp ()
808 Return the current write position in the stream.
811 @deftypefn Method ostream& ostream::seekp (streampos @var{loc})
812 Reset the output position to @var{loc} (which is usually the result of a
813 previous call to @code{ostream::tellp}). @var{loc} specifies an
814 absolute position in the output stream.
817 @deftypefn Method ostream& ostream::seekp (streamoff @var{loc}, @var{rel})
819 Reset the output position to @var{loc}, relative to the beginning, end,
820 or current output position in the stream, as indicated by @var{rel} (a
821 value from the enumeration @code{ios::seekdir}):
825 Interpret @var{loc} as an absolute offset from the beginning of the
829 Interpret @var{loc} as an offset relative to the current output
833 Interpret @var{loc} as an offset from the current end of the output
838 @node Ostream Housekeeping
839 @subsection Miscellaneous @code{ostream} utilities
841 You may need to use these @code{ostream} methods for housekeeping:
843 @deftypefn Method ostream& flush ()
844 Deliver any pending buffered output for this @code{ostream}.
847 @deftypefn Method int ostream::opfx ()
848 @code{opfx} is a @dfn{prefix} method for operations on @code{ostream}
849 objects; it is designed to be called before any further processing. See
850 @code{ostream::osfx} for the converse.
851 @c FIXME-future: specify sometime which methods start with opfx.
853 @code{opfx} tests that the stream is in state @code{good}, and if so
854 flushes any stream tied to this one.
856 The result is @code{1} when @code{opfx} succeeds; else (if the stream state is
857 not @code{good}), the result is @code{0}.
860 @deftypefn Method void ostream::osfx ()
861 @code{osfx} is a @dfn{suffix} method for operations on @code{ostream}
862 objects; it is designed to be called at the conclusion of any processing. All
863 the @code{ostream} methods end by calling @code{osfx}. See
864 @code{ostream::opfx} for the converse.
866 If the @code{unitbuf} flag is set for this stream, @code{osfx} flushes
867 any buffered output for it.
869 If the @code{stdio} flag is set for this stream, @code{osfx} flushes any
870 output buffered for the C output streams @file{stdout} and @file{stderr}.
874 @section Managing input streams: class @code{istream}
876 Class @code{istream} objects are specialized for input; as for
877 @code{ostream}, they are derived from @code{ios}, so you can use any of
878 the general-purpose methods from that base class. Declarations for this
879 class also come from @file{iostream.h}.
881 @deftypefn Constructor {} istream::istream ()
882 When used without arguments, the @code{istream} constructor simply
883 allocates a new @code{ios} object and initializes the input counter (the
884 value reported by @code{istream::gcount}) to @code{0}.
887 @deftypefn Constructor {} istream::istream (streambuf *@var{sb} @w{[, ostream} @var{tie}])
888 You can also call the constructor with one or two arguments. The first
889 argument @var{sb} is a @code{streambuf*}; if you supply this pointer,
890 the constructor uses that @code{streambuf} for input.
891 You can use the second optional argument @var{tie} to specify a related
892 output stream as the initial value for @code{ios::tie}.
894 If you give the @code{istream} a @code{streambuf} explicitly, using
895 this constructor, the @var{sb} is @emph{not} destroyed (or deleted or
896 closed) when the @code{ostream} is destroyed.
900 * Char Input:: Reading one character.
901 * String Input:: Reading strings.
902 * Input Position:: Repositioning an istream.
903 * Istream Housekeeping:: Miscellaneous istream utilities.
907 @subsection Reading one character
909 Use these methods to read a single character from the input stream:
911 @deftypefn Method int istream::get ()
912 Read a single character (or @code{EOF}) from the input stream, returning
913 it (coerced to an unsigned char) as the result.
916 @deftypefn Method istream& istream::get (char& @var{c})
917 Read a single character from the input stream, into @code{&@var{c}}.
920 @deftypefn Method int istream::peek ()
921 Return the next available input character, but @emph{without} changing
922 the current input position.
926 @subsection Reading strings
928 Use these methods to read strings (for example, a line at a time) from
931 @deftypefn Method istream& istream::get (char* @var{c}, int @var{len} @w{[, char} @var{delim}])
932 Read a string from the input stream, into the array at @var{c}.
934 The remaining arguments limit how much to read: up to @samp{len-1}
935 characters, or up to (but not including) the first occurrence in the
936 input of a particular delimiter character @var{delim}---newline
937 (@code{\n}) by default. (Naturally, if the stream reaches end of file
938 first, that too will terminate reading.)
940 If @var{delim} was present in the input, it remains available as if
941 unread; to discard it instead, see @code{iostream::getline}.
943 @code{get} writes @samp{\0} at the end of the string, regardless
944 of which condition terminates the read.
947 @deftypefn Method istream& istream::get (streambuf& @var{sb} @w{[, char} @var{delim}])
948 Read characters from the input stream and copy them on the
949 @code{streambuf} object @var{sb}. Copying ends either just before the
950 next instance of the delimiter character @var{delim} (newline @code{\n}
951 by default), or when either stream ends. If @var{delim} was present in
952 the input, it remains available as if unread.
955 @deftypefn Method istream& istream::getline (@var{charptr}, int @var{len} @w{[, char} @var{delim}])
956 Read a line from the input stream, into the array at @var{charptr}.
957 @var{charptr} may be any of three kinds of pointer: @code{char*},
958 @code{unsigned char*}, or @code{signed char*}.
960 The remaining arguments limit how much to read: up to (but not
961 including) the first occurrence in the input of a line delimiter
962 character @var{delim}---newline (@code{\n}) by default, or up to
963 @samp{len-1} characters (or to end of file, if that happens sooner).
965 If @code{getline} succeeds in reading a ``full line'', it also discards
966 the trailing delimiter character from the input stream. (To preserve it
967 as available input, see the similar form of @code{iostream::get}.)
969 If @var{delim} was @emph{not} found before @var{len} characters or end
970 of file, @code{getline} sets the @code{ios::fail} flag, as well as the
971 @code{ios::eof} flag if appropriate.
973 @code{getline} writes a null character at the end of the string, regardless
974 of which condition terminates the read.
977 @deftypefn Method istream& istream::read (@var{pointer}, int @var{len})
978 Read @var{len} bytes into the location at @var{pointer}, unless the
981 @var{pointer} may be of type @code{char*}, @code{void*}, @code{unsigned
982 char*}, or @code{signed char*}.
984 If the @code{istream} ends before reading @var{len} bytes, @code{read}
985 sets the @code{ios::fail} flag.
988 @deftypefn Method istream& istream::gets (char **@var{s} @w{[, char} @var{delim}])
989 A @sc{gnu} extension, to read an arbitrarily long string
990 from the current input position to the next instance of the @var{delim}
991 character (newline @code{\n} by default).
993 To permit reading a string of arbitrary length, @code{gets} allocates
994 whatever memory is required. Notice that the first argument @var{s} is
995 an address to record a character pointer, rather than the pointer
999 @deftypefn Method istream& istream::scan (const char *format ...)
1000 A @sc{gnu} extension, similar to @code{fscanf(@var{file},
1001 @var{format}, ...)}. The @var{format} is a @code{scanf}-style format
1002 control string, which is used to read the variables in the remainder of
1003 the argument list from the @code{istream}.
1006 @deftypefn Method istream& istream::vscan (const char *format, va_list args)
1007 Like @code{istream::scan}, but takes a single @code{va_list} argument.
1010 @node Input Position
1011 @subsection Repositioning an @code{istream}
1013 Use these methods to control the current input position:
1015 @deftypefn Method streampos istream::tellg ()
1016 Return the current read position, so that you can save it and return to
1017 it later with @code{istream::seekg}.
1020 @deftypefn Method istream& istream::seekg (streampos @var{p})
1021 Reset the input pointer (if the input device permits it) to @var{p},
1022 usually the result of an earlier call to @code{istream::tellg}.
1025 @deftypefn Method istream& istream::seekg (streamoff @var{offset}, ios::seek_dir @var{ref})
1026 Reset the input pointer (if the input device permits it) to @var{offset}
1027 characters from the beginning of the input, the current position, or the
1028 end of input. Specify how to interpret @var{offset} with one of these
1029 values for the second argument:
1033 Interpret @var{loc} as an absolute offset from the beginning of the
1037 Interpret @var{loc} as an offset relative to the current output
1041 Interpret @var{loc} as an offset from the current end of the output
1046 @node Istream Housekeeping
1047 @subsection Miscellaneous @code{istream} utilities
1049 Use these methods for housekeeping on @code{istream} objects:
1051 @deftypefn Method int istream::gcount ()
1052 Report how many characters were read from this @code{istream} in the
1053 last unformatted input operation.
1054 @c FIXME! Define "unformatted input" somewhere...
1057 @deftypefn Method int istream::ipfx (int @var{keepwhite})
1058 Ensure that the @code{istream} object is ready for reading; check for
1059 errors and end of file and flush any tied stream. @code{ipfx} skips
1060 whitespace if you specify @code{0} as the @var{keepwhite}
1061 argument, @emph{and} @code{ios::skipws} is set for this stream.
1063 To avoid skipping whitespace (regardless of the @code{skipws} setting on
1064 the stream), use @code{1} as the argument.
1066 Call @code{istream::ipfx} to simplify writing your own methods for reading
1067 @code{istream} objects.
1070 @deftypefn Method void istream::isfx ()
1071 A placeholder for compliance with the draft @sc{ansi} standard; this
1072 method does nothing whatever.
1074 If you wish to write portable standard-conforming code on @code{istream}
1075 objects, call @code{isfx} after any operation that reads from an
1076 @code{istream}; if @code{istream::ipfx} has any special effects that
1077 must be cancelled when done, @code{istream::isfx} will cancel them.
1080 @deftypefn Method istream& istream::ignore ([int @var{n}] @w{[, int} @var{delim}])
1081 Discard some number of characters pending input. The first optional
1082 argument @var{n} specifies how many characters to skip. The second
1083 optional argument @var{delim} specifies a ``boundary'' character:
1084 @code{ignore} returns immediately if this character appears in the
1087 By default, @var{delim} is @code{EOF}; that is, if you do not specify a
1088 second argument, only the count @var{n} restricts how much to ignore
1089 (while input is still available).
1091 If you do not specify how many characters to ignore, @code{ignore}
1092 returns after discarding only one character.
1095 @deftypefn Method istream& istream::putback (char @var{ch})
1096 Attempts to back up one character, replacing the character backed-up
1097 over by @var{ch}. Returns @code{EOF} if this is not allowed. Putting
1098 back the most recently read character is always allowed. (This method
1099 corresponds to the C function @code{ungetc}.)
1102 @deftypefn Method istream& istream::unget ()
1103 Attempt to back up one character.
1107 @section Input and output together: class @code{iostream}
1109 If you need to use the same stream for input and output, you can use an
1110 object of the class @code{iostream}, which is derived from @emph{both}
1111 @code{istream} and @code{ostream}.
1113 The constructors for @code{iostream} behave just like the constructors
1116 @deftypefn Constructor {} iostream::iostream ()
1117 When used without arguments, the @code{iostream} constructor simply
1118 allocates a new @code{ios} object, and initializes the input counter
1119 (the value reported by @code{istream::gcount}) to @code{0}.
1122 @deftypefn Constructor {} iostream::iostream (streambuf* @var{sb} @w{[, ostream*} @var{tie}])
1123 You can also call a constructor with one or two arguments. The first
1124 argument @var{sb} is a @code{streambuf*}; if you supply this pointer,
1125 the constructor uses that @code{streambuf} for input and output.
1127 You can use the optional second argument @var{tie} (an @code{ostream*})
1128 to specify a related output stream as the initial value for
1132 @cindex @code{iostream} destructor
1133 @cindex destructor for @code{iostream}
1134 As for @code{ostream} and @code{istream}, @code{iostream} simply uses
1135 the @code{ios} destructor. However, an @code{iostream} is not deleted by
1138 You can use all the @code{istream}, @code{ostream}, and @code{ios}
1139 methods with an @code{iostream} object.
1141 @node Files and Strings
1142 @chapter Classes for Files and Strings
1144 There are two very common special cases of input and output: using files,
1145 and using strings in memory.
1147 @code{libio} defines four specialized classes for these cases:
1151 Methods for reading files.
1154 Methods for writing files.
1157 Methods for reading strings from memory.
1160 Methods for writing strings in memory.
1164 * Files:: Reading and writing files.
1165 * Strings:: Reading and writing strings in memory.
1169 @section Reading and writing files
1171 These methods are declared in @file{fstream.h}.
1174 @cindex class @code{ifstream}
1175 You can read data from class @code{ifstream} with any operation from class
1176 @code{istream}. There are also a few specialized facilities:
1178 @deftypefn Constructor {} ifstream::ifstream ()
1179 Make an @code{ifstream} associated with a new file for input. (If you
1180 use this version of the constructor, you need to call
1181 @code{ifstream::open} before actually reading anything)
1184 @deftypefn Constructor {} ifstream::ifstream (int @var{fd})
1185 Make an @code{ifstream} for reading from a file that was already open,
1186 using file descriptor @var{fd}. (This constructor is compatible with
1187 other versions of iostreams for @sc{posix} systems, but is not part of
1188 the @sc{ansi} working paper.)
1191 @deftypefn Constructor {} ifstream::ifstream (const char* @var{fname} @w{[, int} @var{mode} @w{[, int} @var{prot}]])
1192 Open a file @code{*@var{fname}} for this @code{ifstream} object.
1194 By default, the file is opened for input (with @code{ios::in} as
1195 @var{mode}). If you use this constructor, the file will be closed when
1196 the @code{ifstream} is destroyed.
1198 You can use the optional argument @var{mode} to specify how to open the
1199 file, by combining these enumerated values (with @samp{|} bitwise or).
1200 (These values are actually defined in class @code{ios}, so that all
1201 file-related streams may inherit them.) Only some of these modes are
1202 defined in the latest draft @sc{ansi} specification; if portability is
1203 important, you may wish to avoid the others.
1207 Open for input. (Included in @sc{ansi} draft.)
1210 Open for output. (Included in @sc{ansi} draft.)
1213 Set the initial input (or output) position to the end of the file.
1216 Seek to end of file before each write. (Included in @sc{ansi} draft.)
1219 Guarantee a fresh file; discard any contents that were previously
1223 Guarantee an existing file; fail if the specified file did not already
1226 @item ios::noreplace
1227 Guarantee a new file; fail if the specified file already existed.
1230 Open as a binary file (on systems where binary and text files have different
1231 properties, typically how @samp{\n} is mapped; included in @sc{ansi} draft).
1235 The last optional argument @var{prot} is specific to Unix-like systems;
1236 it specifies the file protection (by default @samp{644}).
1239 @deftypefn Method void ifstream::open (const char* @var{fname} @w{[, int} @var{mode} @w{[, int} @var{prot}]])
1240 Open a file explicitly after the associated @code{ifstream} object
1241 already exists (for instance, after using the default constructor). The
1242 arguments, options and defaults all have the same meanings as in the
1243 fully specified @code{ifstream} constructor.
1247 @cindex class @code{ostream}
1248 You can write data to class @code{ofstream} with any operation from class
1249 @code{ostream}. There are also a few specialized facilities:
1251 @deftypefn Constructor {} ofstream::ofstream ()
1252 Make an @code{ofstream} associated with a new file for output.
1255 @deftypefn Constructor {} ofstream::ofstream (int @var{fd})
1256 Make an @code{ofstream} for writing to a file that was already open,
1257 using file descriptor @var{fd}.
1260 @deftypefn Constructor {} ofstream::ofstream (const char* @var{fname} @w{[, int} @var{mode} @w{[, int} @var{prot}]])
1261 Open a file @code{*@var{fname}} for this @code{ofstream} object.
1263 By default, the file is opened for output (with @code{ios::out} as @var{mode}).
1264 You can use the optional argument @var{mode} to specify how to open the
1265 file, just as described for @code{ifstream::ifstream}.
1267 The last optional argument @var{prot} specifies the file protection (by
1268 default @samp{644}).
1271 @deftypefn Destructor {} ofstream::~ofstream ()
1272 The files associated with @code{ofstream} objects are closed when the
1273 corresponding object is destroyed.
1276 @deftypefn Method void ofstream::open (const char* @var{fname} @w{[, int} @var{mode} @w{[, int} @var{prot}]])
1277 Open a file explicitly after the associated @code{ofstream} object
1278 already exists (for instance, after using the default constructor). The
1279 arguments, options and defaults all have the same meanings as in the
1280 fully specified @code{ofstream} constructor.
1284 @cindex class @code{fstream}
1285 The class @code{fstream} combines the facilities of @code{ifstream} and
1286 @code{ofstream}, just as @code{iostream} combines @code{istream} and
1289 @c FIXME-future: say something about fstream constructor, maybe.
1292 @cindex class @code{fstreambase}
1293 The class @code{fstreambase} underlies both @code{ifstream} and
1294 @code{ofstream}. They both inherit this additional method:
1296 @deftypefn Method void fstreambase::close ()
1297 Close the file associated with this object, and set @code{ios::fail} in
1298 this object to mark the event.
1302 @section Reading and writing in memory
1304 @c FIXME!! Per, there's a lot of guesswork here---please check carefully!
1307 @cindex class @code{istrstream}
1309 @cindex class @code{ostrstream}
1311 @cindex class @code{strstream}
1312 @findex strstreambase
1313 @cindex class @code{strstreambase}
1314 @findex strstreambuf
1315 @cindex class @code{strstreambuf}
1316 The classes @code{istrstream}, @code{ostrstream}, and @code{strstream}
1317 provide some additional features for reading and writing strings in
1318 memory---both static strings, and dynamically allocated strings. The
1319 underlying class @code{strstreambase} provides some features common to
1320 all three; @code{strstreambuf} underlies that in turn.
1322 @c FIXME-future: Document strstreambuf methods one day, when we document
1323 @c streambuf more fully.
1325 @deftypefn Constructor {} istrstream::istrstream (const char* @var{str} @w{[, int} @var{size}])
1326 Associate the new input string class @code{istrstream} with an existing
1327 static string starting at @var{str}, of size @var{size}. If you do not
1328 specify @var{size}, the string is treated as a @code{NUL} terminated string.
1331 @deftypefn Constructor {} ostrstream::ostrstream ()
1332 Create a new stream for output to a dynamically managed string, which
1333 will grow as needed.
1336 @deftypefn Constructor {} ostrstream::ostrstream (char* @var{str}, int @var{size} [,int @var{mode}])
1337 A new stream for output to a statically defined string of length
1338 @var{size}, starting at @var{str}. You may optionally specify one of
1339 the modes described for @code{ifstream::ifstream}; if you do not specify
1340 one, the new stream is simply open for output, with mode @code{ios::out}.
1343 @deftypefn Method int ostrstream::pcount ()
1344 Report the current length of the string associated with this @code{ostrstream}.
1347 @deftypefn Method char* ostrstream::str ()
1348 A pointer to the string managed by this @code{ostrstream}. Implies
1349 @samp{ostrstream::freeze()}.
1351 Note that if you want the string to be nul-terminated,
1352 you must do that yourself (perhaps by writing ends to the stream).
1355 @deftypefn Method void ostrstream::freeze ([int @var{n}])
1356 If @var{n} is nonzero (the default), declare that the string associated
1357 with this @code{ostrstream} is not to change dynamically; while frozen,
1358 it will not be reallocated if it needs more space, and it will not be
1359 deallocated when the @code{ostrstream} is destroyed. Use
1360 @samp{freeze(1)} if you refer to the string as a pointer after creating
1361 it via @code{ostrstream} facilities.
1363 @samp{freeze(0)} cancels this declaration, allowing a dynamically
1364 allocated string to be freed when its @code{ostrstream} is destroyed.
1366 If this @code{ostrstream} is already static---that is, if it was created
1367 to manage an existing statically allocated string---@code{freeze} is
1368 unnecessary, and has no effect.
1371 @deftypefn Method int ostrstream::frozen ()
1372 Test whether @code{freeze(1)} is in effect for this string.
1375 @deftypefn Method strstreambuf* strstreambase::rdbuf ()
1376 A pointer to the underlying @code{strstreambuf}.
1380 @chapter Using the @code{streambuf} Layer
1382 The @code{istream} and @code{ostream} classes are meant to handle
1383 conversion between objects in your program and their textual representation.
1385 By contrast, the underlying @code{streambuf} class is for transferring
1386 raw bytes between your program, and input sources or output sinks.
1387 Different @code{streambuf} subclasses connect to different kinds of
1390 The @sc{gnu} implementation of @code{streambuf} is still evolving; we
1391 describe only some of the highlights.
1394 * Areas:: Areas in a streambuf.
1395 * Overflow:: Simple output re-direction
1396 * Formatting:: C-style formatting for streambuf objects.
1397 * Stdiobuf:: Wrappers for C stdio.
1398 * Procbuf:: Reading/writing from/to a pipe
1399 * Backing Up:: Marking and returning to a position.
1400 * Indirectbuf:: Forwarding I/O activity.
1404 @section Areas of a @code{streambuf}
1406 Streambuf buffer management is fairly sophisticated (this is a
1407 nice way to say ``complicated''). The standard protocol
1408 has the following ``areas'':
1413 The @dfn{put area} contains characters waiting for output.
1417 The @dfn{get area} contains characters available for reading.
1420 The @sc{gnu} @code{streambuf} design extends this, but the details are
1423 The following methods are used to manipulate these areas.
1424 These are all protected methods, which are intended to be
1425 used by virtual function in classes derived from @code{streambuf}.
1426 They are also all ANSI/ISO-standard, and the ugly names
1428 (Note that if a pointer points to the 'end' of an area,
1429 it means that it points to the character after the area.)
1431 @deftypefn Method char* streambuf::pbase () const
1432 Returns a pointer to the start of the put area.
1435 @deftypefn Method char* streambuf::epptr () const
1436 Returns a pointer to the end of the put area.
1439 @deftypefn Method char* streambuf::pptr () const
1440 If @code{pptr() < epptr ()}, the @code{pptr()}
1441 returns a pointer to the current put position.
1442 (In that case, the next write will
1443 overwrite @code{*pptr()}, and increment @code{pptr()}.)
1444 Otherwise, there is no put position available
1445 (and the next character written will cause @code{streambuf::overflow}
1449 @deftypefn Method void streambuf::pbump (int @var{N})
1450 Add @var{N} to the current put pointer.
1451 No error checking is done.
1454 @deftypefn Method void streambuf::setp (char* @var{P}, char* @var{E})
1455 Sets the start of the put area to @var{P}, the end of the put area to @var{E},
1456 and the current put pointer to @var{P} (also).
1459 @deftypefn Method char* streambuf::eback () const
1460 Returns a pointer to the start of the get area.
1463 @deftypefn Method char* streambuf::egptr () const
1464 Returns a pointer to the end of the get area.
1467 @deftypefn Method char* streambuf::gptr () const
1468 If @code{gptr() < egptr ()}, then @code{gptr()}
1469 returns a pointer to the current get position.
1470 (In that case the next read will read @code{*gptr()},
1471 and possibly increment @code{gptr()}.)
1472 Otherwise, there is no read position available
1473 (and the next read will cause @code{streambuf::underflow}
1477 @deftypefn Method void streambuf:gbump (int @var{N})
1478 Add @var{N} to the current get pointer.
1479 No error checking is done.
1482 @deftypefn Method void streambuf::setg (char* @var{B}, char* @var{P}, char* @var{E})
1483 Sets the start of the get area to @var{B}, the end of the get area to @var{E},
1484 and the current put pointer to @var{P}.
1488 @section Simple output re-direction by redefining @code{overflow}
1490 Suppose you have a function @code{write_to_window} that
1491 writes characters to a @code{window} object. If you want to use the
1492 ostream function to write to it, here is one (portable) way to do it.
1493 This depends on the default buffering (if any).
1497 #include <iostream.h>
1498 /* Returns number of characters successfully written to @var{win}. */
1499 extern int write_to_window (window* win, char* text, int length);
1501 class windowbuf : public streambuf @{
1504 windowbuf (window* w) @{ win = w; @}
1506 int overflow (int ch);
1507 // Defining xsputn is an optional optimization.
1508 // (streamsize was recently added to ANSI C++, not portable yet.)
1509 streamsize xsputn (char* text, streamsize n);
1512 int windowbuf::sync ()
1513 @{ streamsize n = pptr () - pbase ();
1514 return (n && write_to_window (win, pbase (), n) != n) ? EOF : 0;
1517 int windowbuf::overflow (int ch)
1518 @{ streamsize n = pptr () - pbase ();
1525 if (write_to_window (win, cbuf, 1) != 1)
1528 pbump (-n); // Reset pptr().
1532 streamsize windowbuf::xsputn (char* text, streamsize n)
1533 @{ return sync () == EOF ? 0 : write_to_window (win, text, n); @}
1536 main (int argc, char**argv)
1539 windowbuf wbuf(win);
1540 ostream wstr(&wbuf);
1541 wstr << "Hello world!\n";
1549 @section C-style formatting for @code{streambuf} objects
1551 The @sc{gnu} @code{streambuf} class supports @code{printf}-like
1552 formatting and scanning.
1554 @deftypefn Method int streambuf::form (const char *@var{format}, ...)
1555 Similar to @code{fprintf(@var{file}, @var{format}, ...)}.
1556 The @var{format} is a @code{printf}-style format control string, which is used
1557 to format the (variable number of) arguments, printing the result on
1558 the @code{this} streambuf. The result is the number of characters printed.
1561 @deftypefn Method int streambuf::vform (const char *@var{format}, va_list @var{args})
1562 Similar to @code{vfprintf(@var{file}, @var{format}, @var{args})}.
1563 The @var{format} is a @code{printf}-style format control string, which is used
1564 to format the argument list @var{args}, printing the result on
1565 the @code{this} streambuf. The result is the number of characters printed.
1568 @deftypefn Method int streambuf::scan (const char *@var{format}, ...)
1569 Similar to @code{fscanf(@var{file}, @var{format}, ...)}.
1570 The @var{format} is a @code{scanf}-style format control string, which is used
1571 to read the (variable number of) arguments from the @code{this} streambuf.
1572 The result is the number of items assigned, or @code{EOF} in case of
1573 input failure before any conversion.
1576 @deftypefn Method int streambuf::vscan (const char *@var{format}, va_list @var{args})
1577 Like @code{streambuf::scan}, but takes a single @code{va_list} argument.
1581 @section Wrappers for C @code{stdio}
1583 A @dfn{stdiobuf} is a @code{streambuf} object that points to
1584 a @code{FILE} object (as defined by @code{stdio.h}).
1585 All @code{streambuf} operations on the @code{stdiobuf} are forwarded
1586 to the @code{FILE}. Thus the @code{stdiobuf} object provides a
1587 wrapper around a @code{FILE}, allowing use of @code{streambuf}
1588 operations on a @code{FILE}. This can be useful when mixing
1589 C code with C++ code.
1591 The pre-defined streams @code{cin}, @code{cout}, and @code{cerr} are
1592 normally implemented as @code{stdiobuf} objects that point to
1593 respectively @code{stdin}, @code{stdout}, and @code{stderr}. This is
1594 convenient, but it does cost some extra overhead.
1596 If you set things up to use the implementation of @code{stdio} provided
1597 with this library, then @code{cin}, @code{cout}, and @code{cerr} will be
1598 set up to use @code{stdiobuf} objects, since you get their benefits
1599 for free. @xref{Stdio,,C Input and Output}.
1602 @c FIXME-future: setbuf is not yet documented, hence this para is not useful.
1603 Note that if you use @code{setbuf} to give a buffer to a @code{stdiobuf},
1604 that buffer will provide intermediate buffering in addition that
1605 whatever is done by the @code{FILE}.
1609 @section Reading/writing from/to a pipe
1611 The @dfn{procbuf} class is a @sc{gnu} extension. It is derived from
1612 @code{streambuf}. A @code{procbuf} can be @dfn{closed} (in which case
1613 it does nothing), or @dfn{open} (in which case it allows communicating
1614 through a pipe with some other program).
1616 @deftypefn Constructor {} procbuf::procbuf ()
1617 Creates a @code{procbuf} in a @dfn{closed} state.
1620 @deftypefn Method procbuf* procbuf::open (const char *@var{command}, int @var{mode})
1621 Uses the shell (@file{/bin/sh}) to run a program specified by @var{command}.
1623 If @var{mode} is @samp{ios::in}, standard output from the program is sent
1624 to a pipe; you can read from the pipe by reading from the
1625 @code{procbuf}. (This is similar to @w{@samp{popen(@var{command}, "r")}}.)
1627 If @var{mode} is @samp{ios::out}, output written to the
1628 @code{procbuf} is written to a pipe; the program is set up to read its
1629 standard input from (the other end of) the pipe. (This is similar to
1630 @w{@samp{popen(@var{command}, "w")}}.)
1632 The @code{procbuf} must start out in the @dfn{closed} state.
1633 Returns @samp{*this} on success, and @samp{NULL} on failure.
1636 @deftypefn Constructor {} procbuf::procbuf (const char *@var{command}, int @var{mode})
1637 Calls @samp{procbuf::open (@var{command}, @var{mode})}.
1640 @deftypefn Method procbuf* procbuf::close ()
1641 Waits for the program to finish executing,
1642 and then cleans up the resources used.
1643 Returns @samp{*this} on success, and @samp{NULL} on failure.
1646 @deftypefn Destructor {} procbuf::~procbuf ()
1647 Calls @samp{procbuf::close}.
1653 The @sc{gnu} iostream library allows you to ask a @code{streambuf} to
1654 remember the current position. This allows you to go back to this
1655 position later, after reading further. You can back up arbitrary
1656 amounts, even on unbuffered files or multiple buffers' worth, as long as
1657 you tell the library in advance. This unbounded backup is very useful
1658 for scanning and parsing applications. This example shows a typical
1663 // Read either "dog", "hound", or "hounddog".
1664 // If "dog" is found, return 1.
1665 // If "hound" is found, return 2.
1666 // If "hounddog" is found, return 3.
1667 // If none of these are found, return -1.
1668 int my_scan(streambuf* sb)
1670 streammarker fence(sb);
1672 // Try reading "hounddog":
1673 if (sb->sgetn(buffer, 8) == 8
1674 && strncmp(buffer, "hounddog", 8) == 0)
1676 // No, no "hounddog": Back up to 'fence'
1677 sb->seekmark(fence); //
1678 // ... and try reading "dog":
1679 if (sb->sgetn(buffer, 3) == 3
1680 && strncmp(buffer, "dog", 3) == 0)
1682 // No, no "dog" either: Back up to 'fence'
1683 sb->seekmark(fence); //
1684 // ... and try reading "hound":
1685 if (sb->sgetn(buffer, 5) == 5
1686 && strncmp(buffer, "hound", 5) == 0)
1688 // No, no "hound" either: Back up and signal failure.
1689 sb->seekmark(fence); // Backup to 'fence'
1695 @deftypefn Constructor {} streammarker::streammarker (streambuf* @var{sbuf})
1696 Create a @code{streammarker} associated with @var{sbuf}
1697 that remembers the current position of the get pointer.
1700 @deftypefn Method int streammarker::delta (streammarker& @var{mark2})
1701 Return the difference between the get positions corresponding
1702 to @code{*this} and @var{mark2} (which must point into the same
1703 @code{streambuffer} as @code{this}).
1706 @deftypefn Method int streammarker::delta ()
1707 Return the position relative to the streambuffer's current get position.
1710 @deftypefn Method int streambuf::seekmark (streammarker& @var{mark})
1711 Move the get pointer to where it (logically) was when @var{mark}
1716 @section Forwarding I/O activity
1718 An @dfn{indirectbuf} is one that forwards all of its I/O requests
1719 to another streambuf.
1722 @c FIXME-future: get_stream and put_stream are so far undocumented.
1723 All get-related requests are sent to get_stream().
1724 All put-related requests are sent to put_stream().
1727 An @code{indirectbuf} can be used to implement Common Lisp
1728 synonym-streams and two-way-streams:
1731 class synonymbuf : public indirectbuf @{
1733 synonymbuf(Symbol *s) @{ sym = s; @}
1734 virtual streambuf *lookup_stream(int mode) @{
1735 return coerce_to_streambuf(lookup_value(sym)); @}
1740 @chapter C Input and Output
1742 @code{libio} is distributed with a complete implementation of the ANSI C
1743 @code{stdio} facility. It is implemented using @code{streambuf}
1744 objects. @xref{Stdiobuf,,Wrappers for C @code{stdio}}.
1746 The @code{stdio} package is intended as a replacement for the whatever
1747 @code{stdio} is in your C library.
1749 @c FIXME-future: This is not useful unless we specify what problems.
1750 It can co-exist with C libraries that have alternate implementations of
1751 stdio, but there may be some problems.
1753 Since @code{stdio} works best when you build @code{libc} to contain it, and
1754 that may be inconvenient, it is not installed by default.
1756 Extensions beyond @sc{ansi}:
1760 A stdio @code{FILE} is identical to a streambuf.
1761 Hence there is no need to worry about synchronizing C and C++
1762 input/output---they are by definition always synchronized.
1765 If you create a new streambuf sub-class (in C++), you can use it as a
1766 @code{FILE} from C. Thus the system is extensible using the standard
1767 @code{streambuf} protocol.
1770 You can arbitrarily mix reading and writing, without having to seek
1774 Unbounded @code{ungetc()} buffer.
1778 @c FIXME-future: Per says this is not ready to go public at v0.5
1779 @node Libio buffer management
1780 @chapter Libio buffer management
1782 The libio user functions present an abstract sequence of characters,
1783 that they read and write from. A number of buffers are used to go
1784 between the user program and the abstract sequence. These buffers are
1785 concrete arrays of characters that contain some sub-sequence of the
1788 The libio buffer management protocol is fairly complex. Its design is
1789 based on the C++ @code{streambuf} protocol, so that the C++
1790 @code{streambuf} classes can be trivially implemented on top of the
1793 The @dfn{write area} contains characters waiting for output.
1795 The @dfn{read area} contains characters available for reading.
1797 The @dfn{reserve area} is available to virtual methods.
1798 Usually, the get and/or put areas are part of the reserve area.
1800 The @dfn{main get area} contains characters that have
1801 been read in from the character source, but not yet
1802 read by the application.
1804 The @dfn{backup area} contains previously read data that is being saved
1805 because of a user request, or that have been "unread" (put back).
1809 @c Per says this design is not finished
1810 @node Streambuf internals
1811 @chapter Streambuf internals
1814 * Buffer management::
1815 * Filebuf internals::
1818 @node Buffer management
1819 @section Buffer management
1823 NOTE: This chapter is due for an update.
1825 Streambuf buffer management is fairly sophisticated (this is a
1826 nice way to say "complicated"). The standard protocol
1827 has the following "areas":
1832 The @dfn{put area} contains characters waiting for output.
1835 The @dfn{get area} contains characters available for reading.
1836 @cindex reserve area
1838 The @dfn{reserve area} is available to virtual methods.
1839 Usually, the get and/or put areas are part of the reserve area.
1842 The @sc{gnu} @code{streambuf} design extends this by supporting two
1845 @cindex main get area
1847 The @dfn{main get area} contains characters that have
1848 been read in from the character source, but not yet
1849 read by the application.
1852 The @dfn{backup area} contains previously read data that is being
1853 saved because of a user request, or that have been "unread" (putback).
1856 The backup and the main get area are logically contiguous: That is,
1857 the first character of the main get area follows the last character
1860 The @dfn{current get area} is whichever one of the backup or
1861 main get areas that is currently being read from.
1862 The other of the two is the @dfn{non-current get area}.
1864 @subsection Pointers
1866 The following @code{char*} pointers define the various areas.
1868 @deftypefn Method char* streambuf::base ()
1869 The start of the reserve area.
1872 @deftypefn Method char* streambuf::ebuf ()
1873 The end of the reserve area.
1876 @deftypefn Method char* streambuf::Gbase ()
1877 The start of the main get area.
1880 @deftypefn Method char* streambuf::eGptr ()
1881 The end of the main get area.
1884 @deftypefn Method char* streambuf::Bbase ()
1885 The start of the backup area.
1888 @deftypefn Method char* streambuf::Bptr ()
1889 The start of the used part of the backup area.
1890 The area (@code{Bptr()} .. @code{eBptr()}) contains data that has been
1891 pushed back, while (@code{Bbase()} .. @code{eBptr()}) contains unused
1892 space available for future putbacks.
1895 @deftypefn Method char* streambuf::eBptr ()
1896 The end of the backup area.
1899 @deftypefn Method char* streambuf::Nbase ()
1900 The start of the non-current get area (either @code{main_gbase} or @code{backup_gbase}).
1903 @deftypefn Method char* streambuf::eNptr ()
1904 The end of the non-current get area.
1907 @node Filebuf internals
1908 @section Filebuf internals
1910 The @code{filebuf} is used a lot, so it is importamt that it be
1911 efficient. It is also supports rather complex semantics.
1912 so let us examine its implementation.
1914 @subsection Tied read and write pointers
1916 The streambuf model allows completely independent read and write pointers.
1917 However, a @code{filebuf} has only a single logical pointer used
1918 for both reads and writes. Since the @code{streambuf} protocol
1919 uses @code{gptr()} for reading and @code{pptr()} for writing,
1920 we map the logical file pointer into either @code{gptr()} or @code{pptr()}
1925 Reading is allowed when @code{gptr() < egptr()}, which we call get mode.
1928 Writing is allowed when @code{pptr() < epptr()}, which we call put mode.
1932 A @code{filebuf} cannot be in get mode and put mode at the same time.
1934 We have up to two buffers:
1938 The backup area, defined by @code{Bbase()}, @code{Bptr()}, and @code{eBptr()}.
1942 The reserve area, which also contains the main get area.
1943 For an unbuffered file, the (@code{shortbuf()}..@code{shortbuf()+1}) is used,
1944 where @code{shortbuf()} points to a 1-byte buffer that is part of
1949 The file system's idea of the current position is @code{eGptr()}.
1951 Characters that have been written into a buffer but not yet written
1952 out (flushed) to the file systems are those between @code{pbase()}
1955 The end of the valid data bytes is:
1956 @code{pptr() > eGptr() && pptr() < ebuf() ? pptr() : eGptr()}.
1958 If the @code{filebuf} is unbuffered or line buffered,
1959 the @code{eptr()} is @code{pbase()}. This forces a call
1960 to @code{overflow()} on each put of a character.
1961 The logical @code{epptr()} is @code{epptr() ? ebuf() : NULL}.
1962 (If the buffer is read-only, set @code{pbase()}, @code{pptr()},
1963 and @code{epptr()} to @code{NULL}. NOT!)