digitalmars.com                      
Last update Sat Jun 18 16:54:32 2011

IOstream Classes and Functions

This chapter contains descriptions for:

See IOstreams for an overview.

Note:
This version of Digital Mars C++ implements a different iostream class library than previous versions of Digital Mars C++ or Zortech C++. If your code uses iostream classes from previous releases, you must convert to the classes described here; the old classes are not supported.

Manipulators

A manipulator provides a convenient way to work with extractors and inserters. It embeds what is really a function call into a sequence of insertions or extractions. A manipulator appears to be an object inserted or extracted into a stream, but usually it only changes the state of the stream.

For example, instead of writing:

cout.width(8);
cout << val1 << " ";
cout.width(4);
cout << val2 << '\n';
cout.flush();
write:

cout << setw(8) << val1 << " " << setw(4)
   << val2 << endl;
Classes ios, istream, and ostream all implement predefined manipulators. These are simple, taking no arguments such as endl, above, does. A manipulator can also take arguments, such as setw does. Header file defines some of these manipulators and provides the definitions for creating your own manipulators.

Manipulators are logically defined as templates but were introduced before templates were available in the C++ language. They are accordingly defined as macros simulating templates. The macro IOMANIPdeclare(typ) expands to a complete set of definitions for a manipulator taking one parameter of type typ. Due to the nature of the macros, the type parameter must be a simple type name (just an identifier). The header provides the expanded definitions for types int and long.

Simple Manipulators

A manipulator without arguments is a function with one parameter of type reference to stream, and which returns the same type. The streams have predefined overloaded operators that take such a function as a parameter. The manipulator performs whatever operations are necessary on the stream argument, then returns the same stream. For example, this code implements a tab manipulator:

ostream& tab(ostream& s)
{
   s << '\t';
   return s;
}
In the expression cout<< tab, the overloaded operator ostream& operator<< (ostream& (*)(ostream&)) is selected; it calls the manipulator function. The resulting call inserts a tab character into the ostream.

Parameterized Manipulators

A manipulator with a parameter has two parts:

For a given type typ, all arts are declared by the IOMANIPdeclare macro. These are described below.

The following declarations are used in the discussion below:

Variable Declaration
typ Some type name
n An int
l A long
s An ios
i An istream
o An ostream
io An iostream
f An ios& (*) (ios&)
if An istream& (*) (istream&)
of An ostream& (*) (ostream&)
iof An iostream& (*) (iostream&)
s << SMANIP(typ)(f, t)
s << SAPP(typ)(f)(t)
s >> SMANIP(typ)(f, t)
s >> SAPP(typ)(f)(t)
Returns f(s, t). The stream s can also be any of the other stream types i, o, or io.
i >> IMANIP(typ)(if, t)
i >> IAPP(typ)(if)(t)
Returns if(i, t).
o << OMANIP(typ)(of, t)
o << OAPP(typ)(of)(t)
Returns of(o, t).
io << IOMANIP(typ)(iof, t)
io << IOAPP(typ)(iof)(t)
io >> IOMANIP(typ)(iof, t)
io >> IOAPP(typ)(iof)(t)
Returns iof(io, t).
The <iomanip.h> header contains declarations for manipulators taking an int or a long argument (typ in the above presentation). Predefined manipulators are used for changing the state of a stream:

Manipulator Description
o << setw(n)
i >> setw(n)
Sets the field width of stream i or o to n. The next formatted insertion or extraction resets the width to 0.
o << setfill(n)
i >> setfill(n)
Sets the fill character of stream i or o to n.
o << setprecision(n)
i >> setprecision(n)
Sets the precision variable of stream i or o to n.
o << setiosflags(l)
i >> setiosflags(l)
Turns on the ios flags of stream i or o that are set in l.
o << resetiosflags(l)
i >> resetiosflags(l)
Turns off the ios flags of stream i or o that are set in l.
To write a parameterized manipulator:

  1. Declare function manip, and then implement functions manip and apply.
  2. If the manipulator will take an argument of type typ, declare function manip to take one argument of that type, and to return an object of type Xmanip_typ.
  3. Replace X with either s, i, o, or io, if the intention is to manipulate objects of type ios, istream, ostream, or iostream, respectively.
  4. Replace typ with the actual type name. For types int and long, all declarations are in place. For other types, invoke the "template" IOMANIPdeclare(typ).
Function apply is usually static, called by only the manip function. Define it to return a reference to the type of stream to be manipulated, to have a first parameter of that same type, and a second of type typ.

For example, consider the setiosflags manipulator. The manipulator operates on an ios, and takes a long parameter, so it is declared to return type smanip_long. If it operated on an ostream and took an int parameter, it would be declared to return type omanip_int. The manipulator (the manip function) is therefore declared in the header like this:

smanip_long setiosflags(long);
The apply function does not appear in the header; it is never called directly by user code. Code for both functions appears in the implementation module:

// set the flags bitvector according to the bits
// set in b static ios& sios(ios& i, long b)
// private apply function
{
   i.setf(b);
   return i;
}
smanip_long setiosflags(long b)
// public manip function {
   return smanip_long(sios, b);
}

Class filebuf

The filebuf class is a specialization of streambufs using a file as the source or destination of characters. Characters are fetched (input) from a file and consumed by (written to) a file.

A filebuf object has a file attached to it. When filebuf is connected (attached) to an open file, filebuf is said to be open; otherwise it is closed. A file is opened by default with protection mode filebuf::openprot, which is 0644.

If seek operations can be performed on the attached file, class filebuf supports seeks. For example, an ordinary disk file is seekable, the terminal is not. If the attached file allows reading and/ or writing, the filebuf allows fetching and/ or storing. For example, standard input allows only reading, standard output allows only writing. Unlike C stdio calls, no seek is required between gets and puts to the same filebuf. At least four characters of putback are initially allowed.

Class streambuf provides basic streambuf operations. The reserve area is allocated automatically if one is not supplied to a constructor or with a call to filebuf::setbuf (calls to setbuf are usually honored). If the filebuf is unbuffered, each input and output character requires a system call. Pointers get and put act like a single pointer; conceptually, they are tied together.

A filebuf operates on files by way of a Unix-style file descriptor, a small integer passed in system calls. C stdio calls are not used.

Note:
Supplied file descriptors are not checked for validity. The filebuf does not report seek failures.

Member Functions of filebuf

Class filebuf is derived from streambuf, so you can use all the streambuf member functions on objects of class filebuf.

The following functions are members of class filebuf.


filebuf constructors

Header

fstream.h

Prototype

filebuf();
filebuf(int f);
filebuf(int f, char *ptr, int len);

Description

The default constructor filebuf() creates a closed filebuf.

filebuf(f) creates an open filebuf attached to file descriptor f, which is assumed to be open.

filebuf (f, ptr, len) creates an open filebuf attached to file descriptor f, which is assumed to be open. This constructor uses the array of len chars beginning at ptr as the initial reserve area. If ptr is zero or len is not greater than zero, the filebuf is unbuffered.


filebuf::attach

Header

fstream.h

Prototype

filebuf * filebuf::attach(int f);

Description

If filebuf is closed, this function connects it to file descriptor f, which is assumed to be open, and returns the address of filebuf. If filebuf is already open, it ignores f and returns zero.

filebuf::close

Header

fstream.h

Prototype

filebuf * filebuf::close();

Description

This function flushes any pending output, unconditionally closes the file descriptor, and closes filebuf. It returns the address of filebuf, or zero if an error occurs.

filebuf::fd

Header

fstream.h

Prototype

int filebuf::fd();

Description

This function returns the file descriptor attached to filebuf, or EOF if filebuf is not open.

filebuf::is_open

Header

fstream.h

Prototype

int filebuf::is_open();

Description

This function returns non-zero if filebuf is open (connected to a file descriptor), and zero otherwise.

filebuf::open

Header

fstream.h

Prototype

filebuf * filebuf::open(const char *name, int mode, int prot= filebuf::openprot);

Description

If filebuf is not already open, this function opens file name and connects its file descriptor to filebuf; otherwise an error occurs. This function returns the address of filebuf on success, or zero on any failure.

If the file does not exist, and ios::nocreate is not set in mode, open attempts to create the file with the protection bits specified in prot (with default value 0644). Parameter mode is a collection of bits from ios::open_mode, described in fstream::open, which can be or'd together.


filebuf::seekoff

Header

fstream.h

Prototype

streampos filebuf::seekoff(streamoff off, ios::seek_dir dir, int mode);

Description

This function moves the combined get/ put pointer, described in "Class streambuf (Public Interface)", except parameter mode is ignored. It returns the new file position on success, or EOF if a failure occurs.

If filebuf is not open, if the attached file does not support seeking, or if the seek cannot otherwise be performed (such as off either end of the file), the operation fails. The position of the file in the event of an error is undefined.


filebuf::seekpos

Header

fstream.h

Prototype

streampos filebuf::seekpos(streampos pos, int mode=(ios::in | ios::out));

Description

This function is equivalent to the call filebuf. seekoff((streamoff) pos, ios::beg, mode). The value of pos is obtained from a previous call to seekoff or seekpos, or the value zero representing the beginning of the file. It returns the new file position on success, or EOF if a failure occurs.

filebuf::setbuf

Header

fstream.h

Prototype

streambuf *filebuf::setbuf(char *ptr, int len);

Description

If filebuf is open and a reserve area has been allocated, no change is made and setbuf returns zero. Otherwise, the new reserve area becomes the len chars beginning at the location pointed to by ptr, and the function returns the address of filebuf. The function returns the address of the filebuf object, or zero if filebuf is already open and has a reserve area allocated for it.

If ptr is zero or len is not greater than zero, there will be no reserve area and filebuf is unbuffered.


filebuf::sync

Header

fstream.h

Prototype

int filebuf::sync();

Description

This function attempts to synchronize the get/ put pointer with the actual position of the attached file. This might involve flushing unwritten characters or backing up the file over characters already input. It returns zero if successful, otherwise EOF.

To ensure that a group of characters is written to a file at the same time, allocate a reserve area larger than the largest such group, call sync() just before storing the characters, and then call sync() again just after.


Classes fstream, ifstream, and ofstream

Classes fstream, ifstream, and ofstream do the following:

Each class uses a filebuf object as a buffer to coordinate operations between the stream and the file.

Auxiliary class fstreambase is an implementation detail, primarily providing a set of common functions. It is not documented.

Member Functions of fstream, ifstream ofstream

Class fstream is derived from iostream, which in turn is derived from ios. You can use ios and iostreams member functions on fstream objects.

Class ifstream is derived from istream, which in turn is derived from ios. You can use ios and istreams member functions on ifstream objects.

The following functions are members of fstream, ifstream, and ofstream class. The notation Xstream is used to collectively describe the member functions.


Xstream constructors

Header

fstream.h

Prototype

Xstream();
Xstream(int f);
Xstream(const char *name, int mode = ios::in, int prot = filebuf::openprot);
Xstream(int f, char *ptr, int len);

Description

The default constructor Xstream() constructs a closed xstream, not connected to any file.

Xstream(f) constructs an Xstream attached to file descriptor f, which must already be open; It does not test for this condition. The file will not be closed automatically when the stream is destroyed.

Xstream(name, mode, prot) constructs an Xstream and opens file name using mode for the Xstream::open mode bits and prot for the file protection bits. The default open mode is input for an ifstream and output for an ofstream. The default protection is filebuf::openprot, which is 0644. Errors will be stored in the Xstream error state; see "Error States" in the description of class ios. The file closes automatically when the stream is destroyed.

Xstream(f, ptr, len) constructs an Xstream attached to file descriptor f, which must already be open; it does not test for this condition. The filebuf uses len chars beginning at the location pointed to by ptr as the buffer (reserve area). If ptr is zero or len is not greater than zero, there will be no reserve area and filebuf will be unbuffered. The file will not be closed automatically when the stream is destroyed.


Xstream::attach

Header

fstream.h

Prototype

Xstream::attach(int f);

Description

This function connects Xstream to an open file descriptor f. If Xstream is already connected to a file, it ignores the request, and sets ios::failbit in the Xstream error state. The attached file will not be closed automatically when the stream is destroyed.

Xstream::close

Header

fstream.h

Prototype

Xstream::close();

Description

This function closes the associated filebuf and disconnects the file from Xstream. If the filebuf's close call succeeds, it clears the error state; otherwise it sets ios::failbit in the Xstream error state.

Xstream::open

Header

fstream.h

Prototype

Xstream::open(const car *name, int mode= ios::in, int prot= filebuf::openprot);

Description

This function opens file name and connects its file descriptor to Xstream. If the file does not exist, and ios::nocreate is not set in mode, open attempts to create the file with the protection bits specified in prot (with default value 0644). Parameter mode is a collection of bits from ios::open_mode that can be or'd together. The opened file closes automatically when the stream is destroyed. The following creation modes are supported:

Mode Description
ios::app Initially seeks to the end of the file. Any subsequent write operation always appends to the end of the file. This flag implies ios::out.
ios::ate Initially seeks to the end of the file. This flag does not imply ios::out, but only begins operations at end of file.
ios::in Opens the file for input. Construction or opening of an ifstream always implies this bit; the bit need not be set. When set for an fstream, it means that input is allowed if possible. When set for an ofstream, it means that the file is not truncated when it is opened.
ios::nocreate If the file does not already exist, do not create it; open will fail in this case. This bit makes sense only when opening for output.
ios::noreplace The file must not already exist; otherwise open fails. This bit makes sense only when opening for output.
ios::out Open the file for output. Construction or opening of an ofstream always implies this bit, meaning the bit need not be set. When set for an fstream, it means that output is allowed if possible. This bit can be set for an ifstream, but output to the file is not permitted.
ios::trunc If the file exists, truncate to zero length upon opening it. When ios::out is specified or implied and neither ios::ate nor ios::app is specified, this bit is implied. This bit makes sense only when opening for output.

Xstream::rdbuf

Header

fstream.h

Prototype

filebuf *Xstream::rdbuf();

Description

This function returns a pointer to the filebuf associated with Xstream. It works like its counterparts in the base classes, except that its return type is specifically a filebuf.

Xstream::setbuf

Header

fstream.h

Prototype

Xstream::setbuf(char *ptr, int len);

Description

This function sets up a buffer of len chars at ptr as the reserve area. It calls filebuf::setbuf, and uses its return value to adjust the error state of Xstream. That is, it clears the error state on success, and sets ios::failbit on error.

Class ifstream

Class ifstream, a specialization of class istream, implements input streams for files. It uses a filebuf object as a buffer to coordinate operations between the stream and the file.

The section "Classes fstream, ifstream, and ofstream" discusses fstream, ifstream, and ofstream together, using the notation Xstream.


Class ios

Class ios is a virtual base class of all stream objects. It describes common aspects of input and output streams, such as tracking errors, controlling representation and interpretation of numbers, and monitoring buffers. ios also provides the basic state and formatting data for a stream.

Class ios defines several enumerations and collection of functions. Although you never create an object of class ios, you can use many of its member functions to check the state of a stream and to control formatting.

Class ios Enumerations

Class ios defines the enumerations described below.

io_state

Member functions use these enumerations to keep track of the error state of the stream. See "Error States" for information on how to test these bits. io_state is really a collection of bits, as follows

badbit This bit indicates that some operation on the associated streambuf has failed. Typically, further operations will not succeed, even after clearing the bit. Example situations would be an output error, or immediate end of file on an attempted input operation.
eofbit This bit is normally set when end of file has been reached during an extraction. It is not set as the result of a succesful extraction reaching end of file, but when end of file is reached while attempting further extractions. '' End of file'' in this sense is an abstraction as defined by the streambuf associated with the stream. Normally this bit is not set for output streams.
failbit This bit is set when an attempted extraction or conversion has failed, usually due to unexpected characters. Further attempted extractions will fail until this bit is cleared, to prevent running on after improper input. Usually the stream is still usable, and extraction can be continued after clearing the bit and dealing with the unexpected input.
goodbit This '' bit'' is really the absence of any error bits, and indicates that the stream is in a good state.
hardfail This bit is reserved by the implementation to indicate that the stream cannot be further used. Typically it represents a hardware failure of some kind. The bit cannot be cleared by any publicly accessible function.
open_mode
These enumerations are described with function fstream::open.

seek_dir
These enumerations are described in the section "Class streambuf (Public Interface)", under the function streambuf::seekoff.

Formatting Flags
Member functions use these enumerations of anonymous type to control input and output formatting. See "Format Control".

Constructors and Assignment

Class ios defines the following constructors, which are described in the "Member Functions of ios" section.

ios(sbptr)
ios()           // protected
init(sbptr)     // protected
ios(iosref)     // private

Error States

Functions that enable testing and adjusting the error state bits, are:

Function Description
bad() Checks whether the stream can be used.
clear(flags) Clears the error state.
eof() Checks whether the eofbit is set.
fail() Checks whether the operation failed.
good() Checks whether any error state bits are set.
rdstate() Returns the error state bits of a stream.

Other Status Testing

It is often convenient to be able to test the state of a stream directly. Since typical insertion and extraction operators return a reference to the stream, you can test the return values of the operations. Two operators are defined to permit this testing: void* and !.

The operator void* ()
You can use an explict cast of a stream to void*, or use a stream in a boolean context to test its state. The result is 0 if any of failbit, badbit, or hardfail is set. The result is a non-zero pointer if the stream is in a good or eof state. For example:

if(cout) ... // next output should succeed
if(cin >> x) ... // input to x succeeded
The operator ! ()
This operator provides the inverse of the above testing. The result is non-zero if any of failbit, badbit, or hardfail is set, and zero otherwise. For example:

if(!cout) ... // output will not succeed
if(!(cin >> x)) ... // input to x failed

Format Control

A ios object maintains a format state that is controlled by formatting flags, in combination with the three functions fill, width, and precision. The formatting flags are a collection of bits described below, declared as enumerations of an anonymous type. These format bits are kept in a long int and can be manipulated independently via two versions of the flags function.

Formatting flags can be set and cleared independent of other operations. They change only by explicit programmer action.

Formatting Flags
ios defines the following format flags:

Flag Description
skipws If this flag is set, formatted extractors will skip leading whitespace; otherwise, leading whitespace is not skipped. This flag is set by default, allowing free-format input text. Unformatted extractors do not examine this flag.
left
right
internal
These flags control how padding is inserted during formatted operations. At most one of these three flags can be set at one time. The three flags can be addressed as a unit by the static member ios::adjustfield. If left is set, the value is left-adjusted in its field width, meaning that padding is added on the right. If right is set, the value is right-adjusted in its field width, meaning that padding is added on the left. If internal is set, padding is added after any leading base or sign field, and before the value. The default (none of the flags set) is right. The fill character used for padding defaults to the space character, and can be set with the fill function. The amount of padding is determined by the field width as set by the width function. See the section "Manipulators" for more information.
dec
oct
hex
These flags control the conversion base of integer data. At most one of these three flags can be set at one time. The three flags can be addressed as a unit by the static member ios::basefield. Conversions are done in decimal (base 10) if dec is set, in octal (base 8) if oct is set, or in hexadecimal (base 16) if hex is set. If no flag is set, insertions are done in decimal, and extractions are converted according to the C++ rules for representing integer constants. That is, a leading ''0x'' or ''0X'' results in hex conversion, a leading '0' results in octal conversion, and a leading '1' through '9' results in decimal conversion for extraction. The default is none of these bits set. Manipulators dec, oct, and hex can also be used to set the conversion base as described in the section "ios Predefined Manipulators".
showbase If this flag is set, insertions of converted integral values will be in the form used for representing C++ integer constants. That is, octal values will begin with a leading '0', and hexadecimal values will begin with a leading ''0x'' or ''0X'' (see ''uppercase'' below). The default is unset.
showpos If this flag is set, a plus sign ('+') will be added to insertions of converted positive decimal values (including floating point numbers). The default is unset.
uppercase If this flag is set, an uppercase 'X' will be used in insertions of converted hexadecimal values when showbase is set, and an uppercase 'E' will be used for floating point conversions. Otherwise, lowercase 'x' and 'e' will be used, respectively. The default is unset.
fixed
scientific
These flags control the type of conversion used when floating point values are converted for insertion. The two flags can be addressed as a unit by the static member ios::floatfield. The rules for conversion are generally the same as for the C stdio function printf. If scientific is set, 'e' format is used. If fixed is set, 'f' format is used. If neither is set, 'g' format is used (see also uppercase above). The value set by width, if any, is used as the printf field width specification. The value set by precision, if any, is used as the printf precision specification.
showpoint If this flag is set, trailing zeros, or a trailing decimal point, will appear in the conversion of floating point values. The default is to truncate trailing zeros or a trailing decimal point.
unitbuf If an output stream is buffered, the buffer is flushed when it fills, or when it is explicitly flushed. This can result in delayed output, or lost output if the program crashes. A stream can be unbuffered, eliminating delays and lost output, but at the cost of a system call per character output. If the unitbuf flag is set, the buffer will be flushed after each complete insertion. Unit buffering is thus a compromise, providing frequent output at lower cost than unbuffered output, and not requiring extra flush() calls in the program source. In particular, unit buffering can be turned on and off at selected places in the code without changing any other source code. By default, this flag is not set.
stdio This flag causes the C stdio files stdout and stderr to be flushed after each insertion in the stream. This can be useful when C stdio operations on the standard files is mixed with iostreams on other files. By default, this flag is not set.
Format Bit Masks
ios predefinesdefines the following bit mask as type long with the following OR'd definitions. Use them to set and clear specific groups of bits, helping to avoid conflicting specifications:

Bit mask Definition
adjustfield left | right | internal
basefield dec | oct | hex
floatfield fixed | scientific
Format Control Functions
ios defines the following member functions for format control:

Function Description
fill(char) Gets or sets the fill character
flags(long) Gets formatting flags
precision(int) Gets or sets the precision setting
setf(long, long) Sets formatting flags
unsetf(long) Clears any flag bits that are set
width(int) Gets or sets the field width

User-defined Format Flags and Variables

User-defined format flags and variables are provided for derived classes that might need their own. Once allocated for a class, the flags and variables are reserved for the duration of the program; several independent classes can allocate their own flags and variables without conflict. The following functions return values you can use as flags:

Function Description
bitalloc Allocates a flag bit
iword
ipword
Gets a reference to a user-defined status variable.
xalloc Returns an index to be used with iword or ipword.

ios Predefined Manipulators

A manipulator can appear to be an inserted or extracted object, but really only changes the state of the stream. The following manipulators are predefined for use with streams. Additional manipulators are available when you include manip.h file. See the section "Manipulators" for more information.

Manipulator Description
s >> dec
s << dec
Set the conversion base of stream s to 10.
s >> oct
s << oct
Set the conversion base of stream s to 8.
s >> hex
s << hex
Set the conversion base of stream s to 16.
s >> ws Extracts and discards whitespace from stream s. See the overloaded operator >> in class istream.
s << endl Inserts a newline into stream s and flushes the stream. See overloaded operator << in class ostream.
s << ends Inserts a null character ('\0') into stream s to end the string. See class strstream.
s << flush Flushes the stream s. See class ostream.

Member Functions of ios

Class ios is a virtual base class for ostream, istream, and iostream, so you can use any ios member functions on objects of any of these types, and on types derived from them.

The following functions are members of class ios.


ios constructors

Header

iostream.h

Prototype

ios(streambuf* sbptr);
protected:
ios();
void init(streambuf* sbptr);
private:
ios(iosref);
void operator=(ios&);

Description

Historically, a virtual base class requires a default constructor (one with no arguments), because arguments could not be passed to a constructor for a virtual base class. Class ios therefore has a default constructor ios() and a separate intialization function init(sbptr) whose argument is a pointer to a streambuf.

A derived class uses protected constructor ios() by default, and calls initialization function init(sbptr). The argument to init(sbptr) points to the streambuf to be associated with the ios object being constructed, and must not be null. For example:

class istream : virtual public ios { ... };
istream::istream(streambuf* s)
{
   ios::init(s);
   // ...
}
For the constructor of the form ios(sbptr), the streambuf pointed to by sbptr becomes the streambuf associated with the ios being constructed. The pointer must not be null.

The copy constructor ios(iosref) and assignment operator stream2=stream1 are private to prevent copying of ios objects, since the effect of such copying is not well defined. Usually, you want to copy a pointer to the object, or pass a reference to a function.


ios:bad

Header

iostream.h

Prototype

int ios::bad();

Description

Checks if badbit or hardfail is set. Returns non-zero if either is set, otherwise returns zero.

ios:bitalloc

Header

iostream.h

Prototype

long ios::bitalloc();

Description

This static member function returns a long with one previously unallocated flag bit set. This value can then be used as a flag for class-specific purposes (in calls to setf, for example). At least 16 bits are available for allocation. When no bits are available, this function returns zero.

ios:clear

Header

iostream.h

Prototype

ios::clear(int flags= 0);

Description

This function stores its int parameter as the error state of the stream. The value of flags is derived only from the return of rdstate and/ or combinations of the io_state bits. To clear only one bit in the stream state, use something like:

ios::clear(~ios::failbit & ios::rdstate());


ios:eof

Header

iostream.h

Prototype

int ios::eof();

Description

This function returns non-zero if the eofbit is set, and zero otherwise.

ios:fail

Header

iostream.h

Prototype

int ios::fail();

Description

This function returns non-zero if any of failbit, badbit, or hardfail is set, and zero otherwise.

ios:fill

Header

iostream.h

Prototype

char ios::fill();
char ios::fill(char newfill);

Description

fill() returns the current fill character of the stream. The fill character pads an insertion to the designated field width. See the discussion of the flags left, right, and internal in "Format Control".

fill(newfill) returns the old fill character. The default fill character is the space. See the description of the predefined manipulator setfill in the section "Manipulators".


ios:flags

Header

iostream.h

Prototype

long ios::flags();
long ios::flags(long newflags);

Description

flags() returns the current formatting flags of the stream in a long.

flags(newflags) uses the long value of newflags to replace all the formatting flags in the stream. It returns the previous formatting flags in a long.


ios::good

Header

iostream.h

Prototype

int ios::good();

Description

This function returns non-zero if the error state is good; that is, if no bits are set. Otherwise, it returns zero. In particular, it returns zero if eofbit is set.

ios:iword, ios:pword

Header

iostream.h

Prototype

long ios::iword(int i);
void *ios::pword(int i);

Description

When i is an index value returned by a call to ios::xalloc, these functions return a reference to the ith user-defined status variable (word) for class ios. Function iword returns the reference typed as a long; function ipword returns the reference typed as a void*.

Note:
Do not depend on the returned reference being stable for an indefinite period. In particular, any call to ios::xalloc() can invalidate a previous reference.


ios::precision

Header

iostream.h

Prototype

int ios::precision();
int ios::precision(int newprec);

Description

precision() returns the current '' precision'' format state of stream ios. It controls the number of significant digits converted in floating point insertions. See the section "Format Control" .

precision(newprec) sets the '' precision'' format state of stream s to newprec, and returns the old value. The default value is 6. See the description of the predefined manipulator setprecision in the section "Manipulators" for more information.


ios::rdbuf

Header

iostream.h

Prototype

streambuf *ios::rdbuf();

Description

This function returns a pointer to the streambuf associated with the stream. This is part of the construction of a stream, and the buffer class object is not normally changed. This function can be used to get at streambuf functions directly, given a stream object.

ios:rdstate

Header

iostream.h

Prototype

int ios::rdstate();

Description

This function returns the error state bits of stream ios as an int.

ios:setf

Header

iostream.h

Prototype

long ios::setf(long newflags);
long ios::setf(long newflags, long field);

Description

For setf(newflags), each bit that is set in the long value newflags is set in the formatting flags of stream ios. The remaining formatting flags are unaffected. It returns the previous formatting flags in a long. Note that the ios::flags function replaces all the flag bits, while the ios::setf function sets just those bits that are specified.

setf(newflags) is most useful for setting a flag that is not part of a group. setf(newflags, field) is useful for setting one of a group of flags.

For setf(newflags, field), bits that are set in the long value field mark the formatting flags that are replaced by the corresponding bits in the long value newflags. It returns the previous value of the designated flags. Typically, the field value is one of the bit masks basefield, adjustfield, or floatfield (see "Format Bit Masks").

Example

This example sets left-justification, outputs a value, and restores the previous justification:

long oldadjust = cout.setf(ios::left,
   ios::adjustfield);
cout << data;
cout.setf(oldadjust, ios::adjustfield);
This technique ensures that only one of the adjustfield bits is ever set, and allows convenient restoration of the previous status. Using zero for the new value of the field will clear just those flags.

This code clears the integer conversion base to the default state:

cout.setf(0, ios::basefield);

See the descriptions of the predefined manipulators setiosflags and resetiosflags in the "Manipulators" section.

ios::sync_with_stdio

Header

iostream.h

Prototype

ios::sync_with_stdio();

Description

If C stdio and C++ stream operations are performed on the same standard file, synchronization problems will occur. Since each style of I/O has its own buffering, I/O will not occur in the order of program execution.

To solve this synchronization problem, call this static function before doing I/O to standard streams cin, cout, cerr, or clog; the function resets the standard streams to use class stdiobuf. I/O via stdio and streams will then be synchronized. A substantial performance degradation occurs, however, compared to using buffered stream I/O or buffered stdio.

Note:
Call sync_with_stdio only when doing I/O to the same standard input, output, or error file. Using exclusively stdio input functions on stdin and exclusively stream output functions on cout does not cause problems.


ios::tie

Header

iostream.h

Prototype

ostream *ios::tie(ostream *osp);
ostream *ios::tie();

Description

A stream can be '' tied'' to one ostream, kept track of by the tie stream variable. Whenever a stream needs to acquire more input or flush its output, the tied stream, if any, is flushed first. For example, cin is initially tied to cout, so that pending output, such as a prompt, will be flushed before new input is attempted.

tie(osp) sets the tie variable of stream s to the ostream pointed to by input parameter osp, and returns the old value of the tie variable. This code unties a stream while some work is done, and then restores the previous tie:

ostream* oldosp = s.tie(0);
... do something ...
s.tie(oldosp);

tie returns the current value of the tie variable.


ios:unsetf

Header

iostream.h

Prototype

long ios::unsetf(long newflags);

Description

Each bit set in the long value newflags is unset in the formatting flags of stream ios. The remaining formatting flags are unaffected. The function returns a long containing the previous formatting flags.

Function setf sets corresponding flag bits, while function unsetf clears them. See the description of predefined manipulator resetiosflags in "Manipulators" for more information.


ios:width

Header

iostream.h

Prototype

long ios::width();
long ios::width(int newwidth);

Description

width() returns the current field width format state of stream ios. If the field width is zero, inserters will insert only the characters necessary to represent the value being inserted. If the field width is greater than the number of characters needed, the field will be padded with the fill character to the specified width. If the field width is less than the number of characters needed, the width will be extended. Field width represents the minimum field width; it cannot be used to provide truncation to a maximum field width.

width(newwidth) sets the field width format state of stream s to newwidth, and returns the old value. The default value is 0. The field width is reset to zero automatically after every formatted insertion or extraction. It must therefore be reset for each operation requiring a field width. See the description of the predefined manipulator setw in "Manipulators" for more information.


ios::xalloc

Header

iostream.h

Prototype

int ios::xalloc();

Description

This static member function returns a previously unused index into an array of words. A word is big enough to contain a long or a void*. This index can then be used with functions iword or ipword to get a reference to a reserved status variable.

Class istream

Class istream defines the behavior of input streams. It supports formatted and unformatted extraction (input) of data from an associated streambuf.

istream works in combination with class ostream, which defines the behavior of output streams.

Formatted Input (extraction) Functions

These functions work with formatted input. They call the setup function ipfx(0). If it returns zero, no further action takes place. Otherwise, leading whitespace is stripped if ios::skipws is set. If only whitespace remains in the istream, no characters will remain and the ios::failbit will be set.

istream defines the following formatted input function.

istr >> sbufp
This function extracts characters from istr and inserts them into the streambuf pointed to by sbufp. It always returns a reference to istream. You can use this function to copy a stream efficiently, but be sure neither stream is tied. For example:

#include <iostream.h>
main()
{ // copy cin to cout
  cin.tie(0);
  cout.tie(0);
  cin >> cout.rdbuf(); // see ios for
                      // rdbuf return 0;
}
istr >> x
This function extracts characters from istream and converts them according to the type of x. If ipfx returns zero, no characters are extracted and x is unchanged. Errors encountered are recorded in the error state of istream. In general, ios::failbit means the next available characters were not suitable for the type; for example, leading letters for a numeric type, or leading whitespace for any type. Offending characters are not extracted. Generally, ios::badbit means no characters could be extracted, as in attempting to extract past the end of file. These functions always return a reference to istream. User-written functions must conform to these principles and be of the form:

istream& operator>>(istream&, SomeType)

The type of x and the format state of the istream (described in class ios) determine details of the extraction and conversion. These functions do not change the state of the istream, although the width variable is reset to zero after each formatted extraction. The predefined formatted extractors are:

Extractor Description
char&
unsigned char&
Extracts one character and stores it in x.

short&
unsigned short&
int&
unsigned int&
long&
unsigned long&
Extracts characters and converts them to an integral value according to the conversion base in the istream's format flags, and stores the value in x. The first character can be a plus ('+') or minus ('-') sign. The characters are then treated as decimal, octal, or hexadecimal, if the ios::basfield flags are dec, oct, or hex, respectively. If none of these flags is set, the number is interpreted in the same way as integer constants in C++. That is, if the first two characters are "0x" or "0X" the base is hex; otherwise, if the first character is '0' the base is octal; otherwise the base is decimal.

Extraction (and thus conversion) stops with the first non-digit, which is not extracted. Valid digits are '0'-' 7' for octal, '0'-' 9' for decimal, and '0'-' 9', 'a'-' f', 'A'-' F' for hexadecimal. Error flag ios::failbit is set if no valid digits are encountered. A "0x" followed by a non-digit is an error. In case of an error, the value of x is not changed.

float&
double&
Extracts characters and converts them to a floating point value according to the C++ rules for floating point constants, and stores the value in x. The error flag ios::failbit is set if the characters extracted do not begin a well-formed floating point number; some characters can be extracted in this case, depending on at what point the error is detected. In the case of an error, the value of x is not changed.
char*
unsigned char*
Extracts characters and stores them in the array pointed to by x until a whitespace character is encountered. The whitespace is not extracted (but ipfx might have discarded leading whitespace). If the width formatting variable (see the description of class ios) is non-zero, at most width-1 characters are extracted. A terminating null (0) is always stored in x, even when nothing is extracted. The error flag ios::failbit is set if no characters are available for extraction.

Unformatted Input (extraction) Functions

These functions perform conversions on unformatted input. They call the setup function ipfx(1). If a function returns zero, no further action takes place. Leading whitespace is not skipped, and no conversions take place. See descriptions of the functions in "Member Functions of istreams". Unformatted input functions are:

Function Description
get Gets the next character(s) from the stream.
getline Gets lines from the stream.
ignore Gets characters and discards them.
read Gets characters until EOF is encountered.

Positioning Functions

These functions position the get pointer of the streambuf associated with an istream. See the section "Class streambuf (Public Interface)"

Function Description
istream::seekg(pos) Sets the position of the get pointer; returns istream.
istream::seekg(offset, dir) Sets the position of the get pointer; returns istream.
streampos istream::tellg() Returns the current position of the get pointer.

istream Predefined Manipulators

A manipulator can look like an inserted or extracted object, but often only changes the state of the stream. See "Manipulators" and "ios Predefined Manipulators" for more information.

These manipulators are predefined for use with istreams:

Manipulator Description
istr >> manip Equivalent to the call manip(istr).
istr >> dec Sets the conversion base of istr to 10.
istr >> oct Sets the conversion base of istr to 8.
istr >> hex Sets the conversion base of istr to 16.
istr >> ws Extracts and discards consecutive whitespace characters from istr.

Member Functions of istreams

Class istream is derived from class ios, so you can use all of the ios member functions on an istream object.

The following functions are members of class istreams.


istream constructors

Header

iostream.h

Prototype

istream(streambuf *sbufp);

Description

istream(sbufp) associates the streambuf pointed to by sbufp with the stream and initializes the ios state.

istream::gcount

Header

iostream.h

Prototype

istream::gcount

Description

This function returns the number of characters extracted from istr by the last unformatted input function.

Note that formatted input functions might call unformatted input functions, thus changing the count.


istream::get

Header

iostream.h

Prototype

int istream::get();
istream::get(char& c);
istream::get(char *ptr, int count, char delim= '\n');
istream::get(streambuf & sbuf, char delim= '\n');

Description

get() extracts the next character from istream and returns it. It returns EOF if no more characters are available; however, it never sets ios::failbit.

get(c) extracts the next character from istr and stores it in c. It stores EOF if no more characters are available; it sets ios::failbit when attempting to extract beyond EOF. This function always returns a reference to istream.

get(ptr, count, delim) extracts characters from istr and stores them in the char array beginning at ptr. Extraction stops after count-1 characters have been extracted or when a character matching delim is encountered, whichever happens first. If a delim character is encountered, it is not extracted or stored. This function always stores a terminating null (0) even if nothing is extracted. It sets ios::failbit only if EOF is encountered before any characters are stored. This function always returns a reference to istream.

istream::get(sbuf, delim) extracts characters from istr and stores them in the streambuf sbuf. Extraction stops when a character matching delim (or EOF) is encountered, or when a store into sbuf fails, whichever happens first. If a delim character is encountered, it is not extracted or stored. If delim is EOF, extraction stops only when input is exhausted or when a store operation fails. This function sets ios::failbit only if a store into sbuf fails;. it always returns a reference to istream.


istream::getline

Header

iostream.h

Prototype

istream::getline(char *ptr, int count, char delim= '\n');

Description

This function is the same as istream::get(ptr, count, delim), except delim, if encountered, is extracted but not stored. Once count-1 characters have been extracted, the next character is left in istream, even if it is delim. This function always returns a reference to istream.

istream::ignore

Header

iostream.h

Prototype

istream::ignore(int count= 1, int delim= EOF);

Description

Extracts characters from istr and discards them. Extraction stops when a character matching delim is encountered, when count characters have been extracted, or when EOF is encountered, whichever happens first; the delim character is extracted. If delim is EOF, all input is discarded. This function always returns a reference to istream.

istream::ipfx

Header

iostream.h

Prototype

int istream::ipfx(int noform = 0);

Description

This function performs setup procedures common to all extraction operations. Formatted extractors call ipfx(0); unformatted extractors call ipfx(1).

If the error state of istream is non-zero, ipfx returns zero immediately. If a stream is tied to istream (see ios::tie) and noform is zero, the tied stream is flushed. If flag skipws is set for the stream and noform is zero, leading whitespace characters (defined by iswhite, see ctype(3V)), are skipped. This function returns zero if an error condition is encountered; non-zero otherwise.


istream::peek

Header

iostream.h

Prototype

int istream::peek();

Description

This function first calls istream::ipfx(1). If ipfx returns zero or if istr is at EOF, it returns EOF. Otherwise, it returns the next character without extracting it.

istream::putback

Header

iostream.h

Prototype

istream::putback(char c);

Description

If istream::fail() returns non-zero, this function returns without doing anything. Otherwise, it attempts to back up the streambuf associated with istr by pushing back character c.

Because it does not extract, putback does not call ipfx. It may fail, setting ios::failbit. In general, c must match the character ahead of the streambuf's get pointer (normally the last character extracted) -input might come from a read-only in-memory buffer.


istream::read

Header

iostream.h

Prototype

istream::read(char *ptr, int count);

Description

This function extracts characters from istr and stores them in the char array beginning at ptr. Extraction stops after count characters are extracted or when EOF is encountered, whichever happens first. This function always returns a reference to istream.

read sets ios::failbit if EOF is encountered before count characters are extracted. The number of characters extracted can be found by calling istream::gcount().


istream::sync

Header

iostream.h

Prototype

int istream::sync();

Description

This function forces a correspondence between internal data structures and the external source of characters in an implementation-defined manner. It calls the virtual function istream::rdbuf()->sync(); the result depends on the actual type of the buffer class. This function returns EOF if an error occurs.

Class istream_withassign

Class istream_withassign implements the assignment operator for istream objects. Use it to redirect stream input to other streams.

Member Functions of istream_withassign

Class istream_withassign is derived from class istream. You can use all istream and ios member functions on istream_withassign objects. The following functions are members of class istream_withassign.


istream_withassign constructor

Header

iostream.h

Prototype

istream_withassign();

Description

istream_withassign() creates an istream_withassign object that can be assigned to, but performs no initialization.

istream_withassign::operator=

Header

iostream.h

Prototype

istream_withassign::operator=(streambuf *sbufp);
istream_withassign::operator=(istream &istr);

Description

The first function associates the streambuf pointed to by sbufp with the istream_withassign object and completely initializes it. The second function associates the streambuf, associated with istr, with the istream_withassign object, which the constructor completely initializes. These functions return a reference to the object it was assigned to.

Class istrstream

Class istrstream supports stream input using in-memory character arrays. An istrstream uses a strstreambuf as a buffer to hold characters in memory. istrstream performs stream input operations on strings or on text stored in memory.

Member Functions of istrstream

Because class istrstream is derived from class istream, which is in turn derived from ios, you can use all of the member functions of ios and istream on an istrstream object. The following functions are members of class istrstream.


istrstream constructors

Header

iostream.h

Prototype

istrstream(char *ptr);
istrstream(char *ptr, int len);

Description

istrstream(ptr) assumes ptr points to a null-terminated array of characters, which serves as the input source. Null is not part of the input. Seeks, using istream::seekg, are permitted within the range of the array. istrstream(ptr, len) assumes ptr points to an array of characters of length len, which will serve as the input source. Seeks, using seekg, are permitted within the range of the array.

istrstream::rdbuf

Header

iostream.h

Prototype

strstreambuf *istrstream::rdbuf();

Description

This function returns a pointer to the strstreambuf associated with istrstream. It works like its counterparts in the base classes, except that its return type is specifically a strstreambuf*.

Class ofstream

Class ofstream, a specialization of class ostream, implements output streams for files. It uses a filebuf object as a buffer to coordinate operations between the stream and the file.

The section "Classes fstream, ifstream, and ofstream" discusses fstream, ifstream, and ofstream together, using the notation Xstream.


Class ostream

Class ostream defines behavior for output streams. It supports formatted and unformatted insertion (output) of data to an associated streambuf. ostream works in combination with class istream, which defines the behavior of input streams.

Output Prefix and Suffix Functions

These functions perform setup and cleanup actions before and after insertion operations:

Function Description
opfx Performs setup for insertion operations
osfx Performs cleanup after insertion operations
Formatted Output (insertion) Functions

These functions work with formatted output. They call setup function opfx(). If zero returns, no further action takes place. These functions also call osfx() before returning (if opfx succeeded). The following output functions are defined by ostream.

ostr << sbufp

If ostr.opfx() returns non-zero, this function inserts all the characters into ostr that can be extracted from the streambuf pointed to by sbufp. No padding is performed. It returns a reference to ostr.

You can use this function to copy a stream efficiently, but be sure neither stream is tied. For example:

#include <iostream.h>
main()
{   // copy cin to cout
  cin.tie(0);
  cout.tie(0);
  cout << cin.rdbuf();
  // see ios::rdbuf 0;
}
istr << x

If ostr.opfx(0) returns non-zero, this function inserts characters representing x into ostr. If opfx returns zero, no action is taken. Errors encountered are recorded in the error state of istream. These functions always return a reference to ostr. User-written functions must conform to these principles and be of the form:

ostreama& operator<< (ostream&, SomeType)

The type of x and the format state of the ostream (see the section "Format Control" in the discussion of class ios) determine the details of the conversion and insertion. This kind of function does not change the state of the ostream, except that the width variable is reset to zero after each formatted insertion.

Predefined formatted inserters and their conversion rules are:

Predefined inserters Conversion rules
char
unsigned char
Inserts the character x into ostr without conversion.
short
unsigned short
int
unsigned int
long
unsigned long
The representation consists of a sequence of "digits" with no leading zeros. The digits and coversion are octal if ios::oct is set, hexadecimal if ios::hex is set, decimal if ios::dec or none of these is set. For decimal conversion, if x is positive and ios::showpos is set, there is a leading plus sign ('+'); if x is negative there is a leading minus sign ('-'). The octal and hexadecimal conversions are treated as unsigned; no sign is included. If ios::showbase is set, there is a leading '0' for octal conversion and a leading "0x" or "0X" for hexadecimal conversion, depending on whether ios::uppercase is set.
float
double
The value of x is converted according to the current values in ostr of precision, width, ios::scientific, ios::fixed, and ios::uppercase.
char* The representation is the sequence of characters pointed to by x up to but not including the first null (0) character.
void* The pointer is converted as if it were an int and ios::showbase and ios::hex were set.

Unformatted Output (insertion) Functions

These functions work with unformatted output. They do not call opfx() or osfx(). See "Member Functions of ostream".

Function Description
put Inserts a character into the ostream.
write Inserts multiple characters into the ostream.

Positioning Functions

These functions position the put pointer of the streambuf associated with an ostream. See the "Class streambuf (Public Interface)" section.

Function Description
ostr.seekp(pos)
ostr.seekp(off, dir)
Sets the position of the put pointer; returns a reference to ostr.
streampos pos =
ostr.tellp()
Returns the current position of the put pointer.

ostream Predefined Manipulators

A manipulator can appear to be an inserted or extracted object, but it usually changes only the state of the stream. See the "Manipulators" and "ios Predefined Manipulators" sections. These manipulators are predefined for use with ostreams.

Manipulator Description
ostr << manip Equivalent to the call manip(ostr).
ostr << dec Sets the conversion base of ostr to 10.
ostr << oct Sets the conversion base of ostr to 8.
ostr << hex Sets the conversion base of ostr to 16.
ostr << endl Ends a line by inserting newline and flushing ostr.
ostr << ends Ends a string by inserting null (0) character into ostr.
ostr << flush Equivalent to calling ostr.flush().

Member Functions of ostream

Class ostream is derived from class ios; you can use all of the ios member functions on an ostream object. The following functions are members of class ostream.


ostream constructor

Header

iostream.h

Prototype

ostream(streambuf *sbufp);

Description

ostream(sbufp) associates the streambuf pointed to by sbufp with the stream and initializes the ios state.

ostream::flush

Header

iostream.h

Prototype

ostream::flush();

Description

This function causes characters stored in the associated streambuf to be flushed; for example, they are written to the output file. The function returns a reference to ostream.

ostream::opfx

Header

iostream.h

Prototype

int ostream::opfx();

Description

This function performs setup procedures common to all insertion operations. If a stream is tied to ostr (see ios::tie), the tied stream is flushed. If the error state of ostream is non-zero, opfx returns zero immediately. User-defined inserter functions must start by calling opfx.

This function returns zero if an error condition is encountered, non-zero otherwise.


ostream::osfx

Header

iostream.h

Prototype

ostream::osfx();

Description

This function performs cleanup procedures at the conclusion of an insertion operation. If ios::unitbuf is set, flushes the stream. If ios::stdio is set, flushes stdout and stderr. Predefined inserters call osfx, but unformatted output functions do not.

User-defined inserters must call osfx before returning.


ostream::put

Header

iostream.h

Prototype

ostream::put(char c);

Description

This function inserts the character c into ostr. Sets the error state if the operation fails. The function always returns a reference to ostr.

ostream::write

Header

iostream.h

Prototype

ostream::write

Description

This function inserts exactly len characters starting at the beginning of the char array, pointed to by ptr, into ostream. It sets the error state if the operation fails. The function always returns a reference to ostream.

Class ostream_withassign

Class ostream_withassign implements the assignment operator for ostream objects. Use it to redirect stream output to other streams.

Member Functions of ostream_withassign

Because class ostream_withassign is derived from class ostream, you can use all ostream and ios member functions on ostream_withassign objects. The following functions are members of class ostream_withassign.

ostream_withassign constructor

Header

iostream.h

Prototype

ostream_withassign();

Description

ostream_withassign() creates an ostream_withassign object that can be assigned to. However, it performs no initialization.

ostream_withassign::operator=

Header

iostream.h

Prototype

ostream_withassign::operator= (streambuf *sbufp);
ostream_withassign::operator= (ostream & ostr);

Description

The first function associates the streambuf pointed to by sbufp with the ostream_withassign object, completely initializing the object. The second function associates the streambuf, associated with ostr, with the ostream_withassign object, which is completely initialized by the constructor. Each function returns a reference to the object it was assigned to.

Class ostrstream

Class ostrstream is a specialization of class ostream. It supports stream output using in-memory character arrays. An ostrstream uses a strstreambuf as a buffer to hold the characters in memory. Use ostrstream to perform stream output operations on strings or on text stored in memory.

Related classes istrstream and strstream are specializations of classes istream and iostream, respectively.

Member Functions of ostrstream

Class ostrstream is derived from class ostream, which in turn is derived from ios. You can use all of the member functions of ios and ostream on an ostrstream object.

The following functions are members of class ostrstream.


ostrstream constructors

Header

strstream.h

Prototype

ostrstream();
ostrstream(char *ptr, int len, int mode= ios::out);

Description

ostrstream() creates an empty output stream that uses a dynamic (expandable) array of characters (see class strstreambuf). Seeks are permitted within the current bounds of the array. Presumably this stream will be converted to a char* via str() (see below).

ostrstream(ptr, len, mode) creates an output stream using the static (non-expandable) array of len characters starting at ptr. If the ios::ate or ios::app bits are set in mode, the array is assumed to contain a null-terminated string beginning at ptr. Characters are stored beginning at the null character, but never go beyond len characters. If those bits are not set in mode, the array is assumed to contain no data, and characters will be stored beginning at ptr. Seeks are permitted within the range of the array.


ostrstream::pcount

Header

strstream.h

Prototype

int ostrstream::pcount();

Description

This function returns the number of characters stored in the array. It is useful when the array contains binary data or is not null-terminated.

ostrstream::rdbuf

Header

strstream.h

Prototype

strstreambuf *ostrstream::rdbuf();

Description

This function returns a pointer to the strstreambuf associated with ostrstream. It works like its counterparts in the base classes, except that its return type is specifically a strstreambuf*.

Class stdiobuf

The stdiobuf class is a specialization of streambufs using a C stdio FILE structure as an intermediary to the file that is the source or destination of characters. Input, output, and seek operations are reflected in changes to the associated FILE structure. For example, seek functions are implemented in terms of fseek().

The stdiostream class provides a C++ interface to a C stdio FILE structure. Class streambuf implements basic streambuf operations.

Why Use stdiobuf?

The only reason to use stdiobuf is to integrate existing C stdio code and C++ iostream-like code. If possible, use filebuf for new code; filebuf operations are more efficient because they are buffered.

Member Functions of stdiobuf

Class stdiobuf is derived from streambuf, so you can use all of the streambuf member functions on objects of class stdiobuf.

The following functions are members of class stdiobuf.


stdiobuf constructor

Header

stdiostream.h

Prototype

stdiobuf(FILE *fp);

Description

This function constructs a stdiobuf attached to the FILE structure pointed to by fp.

stdiobuf::stdiofile

Header

stdiostream.h

Prototype

FILE *stdiobuf::stdiofile();

Description

This function returns a pointer to the FILE structure associated with stdioiobuf. The function returns a pointer to FILE structure.

Class stdiostream

The stdiostream class provides a C++ interface to a C stdio FILE structure. It has a stdiobuf as its buffer. It is not a full implementation of iostreams; it has only the buffer-class and ios-class functionality. C++ I/O is done via per-character calls to the C stdio functions getc and putc. Buffering does not occur; it would break synchronization of the C and C++ file accesses.

The stdiobuf class provides a specialization of streambufs using a C stdio FILE structure as an intermediary to the actual file that is the source or destination of characters. Basic streambuf operations are implemented in class streambuf.

Why Use stdiostream?

The only reason to use stdiostream is to integrate existing C stdio code and C++ iostream-like code. If possible, use fstream for new code; fstream operations are more efficient because they are buffered.

Member Functions of stdiostream

Class stdiostream is derived from ios so you can use all of the ios member functions on objects of class stdiostream. The following functions are members of class stdiostream.


stdiostream constructor

Header

stdiostream.h

Prototype

stdiobuf *stdiostream::rdbuf();

Description

Constructs a stdiostream attached to the FILE structure pointed to by fp.

stdiostream::rdbuf

Header

stdiostream.h

Prototype

stdiobuf *stdiostream::rdbuf();

Description

Returns a pointer to the stdiobuf associated with stdiostream. It works like ios::rdbuf() except the return type is a stdiobuf.

Class streambuf (Protected Interface)

The streambuf class is an abstract class for implementing buffers associated with input and output streams. It defines the basics from which actual buffer classes are derived.

The protected interface to streambuf provides functions required to derive a user-defined buffer class. You do not typically create objects of type streambuf; buffer objects are of a class type derived from streambuf. The iostream library provides three predefined derived buffer classes: filebuf, strstreambuf, and stdiobuf.

The public interface to streambuf, described in the section "Class streambuf (Public Interface)", provides functions that any stream class can perform its buffer related operations.

Using the Protected Interface to streambuf

The non-virtual functions in this interface are not intended to be over-ridden; they provide low-level buffer management functions. It is the virtual functions that you will often to override.

Where a virtual function's default behavior is suitable for a derived buffer class, you do not have to override it. For example, a buffer class that has no input source need not do anything on underflow except return EOF, the default behavior. Where the default behavior is not appropriate, you must provide a class-specific version of the function. For example, an input buffer connected to a file attempts to read more data on underflow.

A replacement virtual function conforms to the specification of the streambuf version, to ensure other functions that depend on this behavior will continue to work.

The get, put, and reserve Areas

The buffer of a streambuf has three parts: the get area, the put area, and the reserve area. The get area contains characters immediately available for input. The put area holds characters stored for output but not yet consumed by (flushed to) their ultimate destination. The get and put areas can be disjoint or can overlap. The reserve area is the entire buffer, overlapped by the get and put areas. The get and put areas can expand into the remainder of the reserve area. In the course of input and output operations, the sizes of the get and put areas expand and shrink, always bounded by the total buffer size.

The buffer and its three areas are defined by private pointer variables that you read and set using protected member functions. Think of the following pointers as pointing between characters; that is, although a pointer points to a character, it is helpful to conceptualize it as pointing to just before the character.

Non-virtual Functions for Examining Pointers

The protected interface to class streambuf defines the following non-virtual member functions for examining pointers. Their descriptions are in "Member Functions of streambuf (Protected Interface)".

Function Returns
base A pointer to the beginning of the reserve area.
eback The lowest possible value for gptr().
ebuf A pointer just past the end of the reserve area.
egptr The maximum value for gptr().
epptr The maximum possible value for pptr().
gptr A pointer to the next character to be fetched.
pbase The lowest possible value for pptr().
pptr The location of the next character to be stored.

Non-virtual Functions for Setting Pointers

These functions provide the only way to set the pointers. Direct access is disallowed to ensure consistency among the various pointers. Pointer arguments to a function must all be zero to indicate that there is no area (get, put, reserve). Using equal non-zero pointers might result in incorrect behavior.

The protected interface to class streambuf defines the following non-virtual member functions for examining pointers. Their descriptions are in "Member Functions of streambuf (Protected Interface)".

Function Sets Up
setb The buffer.
Setg The get area.
setp The put area.

Virtual Functions

The following virtual functions can be or should be redefined by specialized buffer classes. Replacement functions must meet the specifications listed here to ensure the correct operation of other functions that depend on their behavior. See "Member Functions of streambuf (Protected Interface)" for information on the default behavior of these functions.

Function Description
doallocate Allocates a buffer using new().
overflow Flushes characters to stdout when the put area is full.
pbackfail Handles instances where put operations fail.
seekoff Repositions the get and/or put pointer(s) by some offset.
seekpos Repositions the get and/or put pointer(s) to a specific position.
setbuf Set up a buffer.
sync Synchronizes the streambuf with itscharacter stream.
underflow Gets characters for input when the get area is empty.

Member Functions of streambuf (Protected Interface)

Class streambuf is an abstract class, so use only its derived classes (filebuf, strstreambuf, and stdiobuf) or derive your own class from streambuf.

The protected interface to streambufs defines the following member functions.


streambuf constructors

Header

iostream.h

Prototype

streambuf();
streambuf(char* ptr, int len);
streambuf(streambuf&);
operator=(streambuf&);

Description

As streambuf is intended to be a base class, no streambuf object is meant to be constructed.

streambuf() creates an empty buffer for an empty input stream. streambuf(ptr, len) creates an empty buffer, and makes a reserve area (see below) using the len bytes beginning at the location pointed to by ptr.

The copy constructor streambuf(streambuf&) and assignment operator operator=(streambuf&) are private and not implemented to ensure that a streambuf cannot be copied. Do not copy a streambuf; instead, pass around pointers to one.


streambuf::allocate

Header

iostream.h

Prototype

int streambuf::allocate();

Description

This function is not called by any non-virtual member of streambuf. It tries to set up a reserve area of an unspecified default size. It returns zero and does nothing if a reserve area already exists or if the streambuf is marked unbuffered by a call to streambuf::unbuffered(). Otherwise, it attempts allocation by calling virtual function streambuf::doallocate(). It returns 1 on success, EOF on failure.

streambuf::base

Header

streambuf::base

Prototype

char *streambuf::base();

Description

This function returns a pointer to the beginning of the reserve area.

streambuf::blen

Header

iostream.h

Prototype

int streambuf::blen();

Description

This function returns the size in chars of the reserve area, ebuf() -base().

streambuf::doallocate

Header

iostream.h

Prototype

int streambuf::doallocate();

Description

This function is called by streambuf::allocate() when streambuf::unbuffered() is zero and streambuf::base() is zero. It attempts to make a buffer of suitable size available.

On success it must call setb to establish the reserve area, and then return a value greater than zero. The default behavior is to allocate a buffer using new. If a failure occurs, the function returns EOF.


streambuf::dpb

Header

iostream.h

Prototype

streambuf::void sbuf.dpb();

Description

This function writes all the state variables of the streambuf as text directly to file descriptor 1 (standard output). This information is useful for debugging an implementation.

dpb is a public function that you can call from anywhere in your code for debugging purposes, although it is logically part of the protected interface.


streambuf::eback

Header

iostream.h

Prototype

char *streambuf::eback();

Description

This function returns the lowest possible value for gptr(). The space from eback() through gptr()-1 is available for putting characters back (backing up the get pointer). If eback()==gptr(), an attempted putback operation might fail.

streambuf::gbumps

Header

iostream.h

streambuf::ebuf

Header

iostream.h

Prototype

char *streambuf::ebuf();

Description

This function returns a pointer just past the end of the reserve area. The space from base() through ebuf()-1 is the reserve area. If ebuf()== base(), the stream is unbuffered.

streambuf::egptr

Header

iostream.h

Prototype

char *streambuf::egptr();

Description

This function returns a pointer just past the end of the get area, which constitutes the maximum possible value for gptr().

streambuf::epptr

Header

iostream.h

Prototype

char *streambuf::epptr();

Description

This function returns a pointer just past the end of the put area, which constitutes the maximum possible value for pptr(). The space from pptr() through epptr() is immediately available for storing characters without a flush operation.

Prototype

streambuf::gbump(int n);

Description

This function adds n, a signed quantity, to the get pointer, without any validity checks.

streambuf::gptr

Header

iostream.h

Prototype

char *streambuf::gptr();

Description

This function returns a pointer to the beginning of the get area, and thus to the next character to be fetched (if one exists).

The characters immediately available are from gptr() through egptr()-1. If egptr()<= gptr(), no characters are available.


streambuf::overflow

Header

iostream.h

Prototype

int streambuf::overflow(int c = EOF);

Description

This function is called to consume characters (flush them to output), typically when the put area is full and an attempt is made to store another character. If c is not EOF, overflow must either store or consume the character, following those already in the put area.

The default behavior of the base class version is undefined, so each derived class must define its own overflow. The normal action for a derived class version is to consume the characters in the put area (those between pbase() and pptr()), call setp() to set up a new put area, then store c (using sputc()) if it is not EOF.

The function returns EOF on error, any other value on success.


streambuf::pbackfail

Header

iostream.h

Prototype

int streambuf::pbackfail(int c);

Description

This function is called when an attempt is made to put back the character c and no space is available in the putback area; that is, eback()==gptr().

If this situation can be handled, such as by repositioning an external device, a derived class version of pbackfail should do so and return c. If the character cannot be put back, it returns EOF. The default behavior of the base class version is to return EOF.


streambuf::pbase

Header

iostream.h

Prototype

char *streambuf::pbase();

Description

This function returns a pointer to the beginning of the space available for the put area, which constitutes the lowest possible value for pptr(). The area from pbase() through pptr()-1 represents characters stored in the buffer but not yet consumed.

streambuf::pbump

Header

iostream.h

Prototype

streambuf::pbump(int n);

Description

This function adds n, a signed quantity, to the put pointer, without any validity checks.

streambuf::pptr

Header

iostream.h

Prototype

char *streambuf::pptr();

Description

This function returns a pointer to the beginning of the put area, and thus to the location of the next character that is stored (if possible).

streambuf::seekoff

Header

iostream.h

Prototype

streampos streambuf::seekoff(streamoff off,
ios::seek_dir dir,
int mode = (ios::in | ios::out));

Description

See streambuf::seekoff in "Class streambuf (Public Interface)" for a description of its parameters, return value, and use.

This function modifies the abstract get and put pointers, as opposed to gptr() and pptr() specifically, if possible. A derived class version returns EOF if the stream does not support repositioning or if there is any error, and the new position otherwise. The default behavior of the base class version is to return EOF.


streambuf::seekpos

Header

iostream.h

Prototype

streampos streambuf::seekpos(streampos pos, int mode=(ios::in | ios::out));

Description

See streambuf::seekpos in "Class streambuf (Public Interface)" for a description of its parameters, return value, and use.

This function modifies the abstract get and put pointers, as opposed to gptr and pptr specifically, if possible. The default behavior of the base class version is to return the value of streambuf::seekoff((streamoff) pos, ios::beg, mode ). Thus it is usually only necessary to implement seekoff in a derived class, and inherit the base class seekpos.


streambuf::setbuf

Header

iostream.h

Prototype

streambuf *streambuf::setbuf(char *ptr, int len);

Description

A call of this function is a request to use the array of len bytes starting at the location pointed to by ptr as the buffer area. Setting ptr to zero or len to less than or equal to zero requests an unbuffered state.

A derived class version can choose to ignore the request. It returns the address of sbuf if it accepts the request, EOF otherwise. The default behavior of the base class version is to honor the request if there is no reserve area.


streambuf::sync

Header

iostream.h

Prototype

int streambuf::sync();

Description

This function synchronizes the streambuf with its actual stream of characters. A derived class version flushes any characters in the put area to their final destination, and if possible give back any character in the input buffer to its source.

The default behavior of the base class version is to return zero if an input or output character is not penting (streambuf::in_avail() and streambuf::out_waiting() are both zero), and return EOF otherwise.


streambuf::unbuffered

Header

iostream.h

Prototype

int streambuf::unbuffered();
streambuf::unbuffered(int i);

Description

A streambuf has a private variable that keeps track of whether the stream is buffered or unbuffered, independent of whether a reserve area has been assigned. This variable is used mainly to control whether allocate() will actually allocate a reserve area.

unbuffered() returns nonzero if the variable is set; zero otherwise. unbuffered(i) sets the variable if i is nonzero; clears it otherwise.


streambuf::underflow

Header

iostream.h

Prototype

int i = sbuf.underflow

Description

This function supplies characters for input (from some source) when the get area is empty, although it can be called at other times.

If the get area is not empty, the first character is returned, without advancing the get pointer. If the get area is empty the function establishes a new get area, acquires new input, and returns the first character, if one exists.

If no input characters are available, it leaves an empty get area and returns EOF. The default behavior of the base class version is undefined; each derived class must define how to handle underflow.

Class streambuf (Public Interface)

The streambuf class is an abstract class for implementing buffers associated with input and output streams. It defines the basics from which actual buffer classes are derived.

The public interface to streambuf provides functions that any stream class might need to perform its buffer related operations. You do not typically create objects of type streambuf; buffer objects would be of a class type derived from streambuf. The section "Class streambuf (Protected Interface)" describes the protected interface necessary to create such derived classes.

An object of class streambuf consists of a sequence of characters and one or two pointers that define where in memory where the next character will be stored (the put area) and/ or fetched (the get area). A buffer class intended only for input (or output) will have only the get (or put) pointer. A buffer class intended for both input and output will have both pointers.

The get and put pointers point between characters in the sequence. The next character to be fetched from an input buffer is the one just after the get pointer. The next character placed into an output stream will be stored just after the put pointer. When at the beginning of the sequence, a pointer points just before the first character; at the end of the sequence it points just after the last character.

Buffering Strategies

The iostream library supports several buffering strategies. Queue-like buffers, such as strstreambufs, have independent get and put pointers. A strstreambuf object is an in-memory array of characters, and supports stores and fetches at arbitrary locations. File-like buffers, such as filebuf objects, can permit both get and put operations, but effectively only one pointer exists; the next get or put will always be at the current location. (In practice two pointers can exist, but they always point to the same place.)

The streambuf uses an array of characters as the buffer, and calls upon virtual functions to fill an empty input buffer or to flush a full output buffer. (See "Class streambuf (Protected Interface)" for details.) The storing, fetching, and pointer manipulation functions are generally inline for maximum efficiency.

The public interface to streambufs defines the followingfunctions. Their descriptionsare in "Member Functions of streambuf (Public Interface)".

Input Functions

getc Gets the character after the get pointer.
in_avail Counts the number of characters in the get area.
sbumpc Moves the get pointer forward one position and gets the character it moved past.
sgetn Gets a string of characters.
snextc Moves the get pointer forward one position.
sputbackc Puts a character before the current pointer location.
stossc Moves past the next character without getting it.

Output Functions

out_waiting Repositions the get/put pointer(s).
sputc Puts a character after the pointer.
sputn Puts a string after the pointer.

Positioning Functions

seekoff Repositions the get/put pointer(s).
seekpos Repositions the get/put pointer(s).
sync Synchronizes the streambuf with the corresponding stream.

Other Functions

setbuf Sets up a buffer area.

Member Functions of streambuf (Public Interface)

Class streambuf is an abstract class, so you must use only its derived classes (filebuf, strstreambuf, and stdiobuf) or derive a class from streambuf yourself. The public interface to streambufs defines the following member functions.


streambuf::in_avail

Header

iostream.h

Prototype

int streambuf::in_avail();

Description

This function returns the number of characters immediately available in the get area. It ensures that i characters can be fetched without error, and without accessing any external device.

streambuf::out_waiting

Header

iostream.h

Prototype

int streambuf::out_waiting();

Description

This function returns the number of characters in the put area; that is, the number of characters pending output to the ultimate destination.

streambuf::sbumpc

Header

iostream.h

Prototype

int streambuf::sbumpc();

Description

This function should probably have been called "sgetc". It moves the get pointer forward one position and returns the character it moved past. If the get pointer is currently at the end of the sequence, this function returns EOF.

streambuf::seekoff

Header

iostream.h

Prototype

streampos streambuf::seekoff(streamoff off, ios::seek_dir dir, int mode=(ios::in | ios::out));

Description

This function repositions the get and/or the put pointers, depending on the bits set in mode. If mode is set to ios::in, the get pointer is moved; if mode is ios::out, the put pointer is moved. The distance to move is off, a signed quantity. Values for dir are:
ios::beg Move off bytes from the beginning of the stream
ios::cur Move off bytes from the current position
ios::end Move off bytes from the end of the stream
Note: Not all streams support positioning.

The function returns the new position, or EOF if the stream could not be positioned. The position returned (of type streampos) must not be the subject of an arithmetic operation; it must be treated as a "magic" value.


streambuf::seekpos

Header

iostream.h

Prototype

streampos streambuf::seekpos(streampos pos,
int mode=(ios::in | ios::out));

Description

This function repositions the get or put pointer, depending on the bits set in mode, to position pos. If mode is set to ios::in, the get pointer is moved; if mode is ios::out, the put pointer is moved. The value of pos must be one that was returned by a previous call of seekoff or seekpos. Special values are: (streampos) 0 The beginning of the stream (streampos) EOF Error indicator

streambuf::setbuf

Header

iostream.h

Prototype

streambuf *streambuf::setbuf(char *ptr, int len);

Description

This function attempts to use array len bytes starting at the location pointed to by ptr as the buffer area. Setting ptr to zero or len to less than or equal to zero requests an unbuffered state. Depending on the implementation of the derived class, honoring the request might not be possible. The function returns a pointer to the streambuf on success, or zero if the request cannot be honored. This function logically belongs in the protected interface to streambuf, but is in the public interface for compatibility with the original stream package.

streambuf::sgetc

Header

iostream.h

Prototype

int streambuf::sgetc();

Description

This function returns the character after the get pointer, or EOF if the get pointer is at the end of the sequence. Despite its name, this function does not move the get pointer.

streambuf::sgetn

Header

iostream.h

Prototype

int streambuf::ssgetn(char *ptr, int len);

Description

This function gets the next len characters following the get pointer, copying them to the char array pointed to by ptr; it advances the get pointer past the last character fetched. If fewer than len characters remain, it gets as many as are available.

streambuf::snextc

Header

iostream.h

Prototype

int streambuf::snextc();

Description

This function moves the get pointer forward one position, and then returns the character after the get pointer's new position. If the get pointer is at the end of the sequence before or after the call to this function (meaning that no character is available), this function returns EOF. For example, if the input buffer looks like this:

abc|def

where '| ' marks the position of the get pointer, snextc advances the get pointer and returns 'e'.


streambuf::sputbackc

Header

iostream.h

Prototype

int streambuf::sputbackc(char c);

Description

This function attempts to move the get pointer back one character and put c at the new location. Depending on the underlying buffer mechanism, moving the pointer back or storing c at that location might not be possible. Therefore, the function's effect is uncertain if c is not the same as the character just ahead of the get pointer.

Depending on the underlying buffer mechanism, this function might require resynchronization with an external device.

The function returns the character that was put back, or EOF if the operation fails. Failure depends on the implementation of the actual buffer class, but would probably include already being at the beginning of a device.


streambuf::sputc

Header

iostream.h

Prototype

int streambuf::sputc(int c);

Description

This function stores c just after the put pointer, and advances the pointer one position, possibly extending the sequence.

The function returns the character stored, or EOF on error. What constitutes an error depends on the implementation of the actual derived buffer class.


streambuf::sputn

Header

iostream.h

Prototype

int streambuf::sputn(const char *ptr, int len);

Description

From the location pointed to by ptr, this function stores exactly len characters after the put pointer, advancing the put pointer just past the last character. The function returns the number of characters stored, which is len. Fewer than len characters stored indicates an error.

streambuf::stossc

Header

iostream.h

Prototype

streambuf::stossc();

Description

This function moves the get pointer forward one position. Use stossc in combination with sgetc (which provides lookahead) to implement a scanner without putting back characters.

streambuf::sync

Header

iostream.h

Prototype

streambuf::sync

Description

This function synchronizes the streambuf with its actual stream of characters. How it operates depends on the particular derived buffer class. Generally, any character in the put area is flushed to its final destination, and any character in the input buffer is given back to its source, if possible. This generally means that in_avail() and out_waiting() each return zero after a call to sync().

The function returns zero if successful, or EOF if an error occurs.


Class strstream

Class strstream provides functions for stream I/O using in-memory character arrays. A strstream uses a strstreambuf as a buffer to hold the characters in memory. Use strstream to do stream I/O on strings or on text stored in memory.

Related classes istrstream and ostrstream are derived from classes istream and ostream, respectively; they also perform I/O using character arrays.

Auxiliary class strstreambase is an implementation detail to provide a set of common functions. It is not documented.

Member Functions of strstream

Class strstream is derived from class iostream, which in turn is derived from class ios. You can use all of the member functions of ios and iostream on a strstream object. The following functions are members of class strstream.


strstream constructors

Header

strstream.h

Prototype

strstream();
strstream(char *ptr, int len, int mode);

Description

strstream() creates an empty bidirectional stream, which uses a dynamic (expandable) array of characters (see class strstreambuf). Seeks are permitted within the current bounds of the array.

strstream(ptr, len, mode) creates a bidirectional stream using the static (non-expandable) array of len characters starting at ptr. If mode is set to ios::ate or ios::app bits, the array is assumed to contain a null-terminated string beginning at ptr. Characters are stored beginning at the null character, but never go beyond len characters. If those bits are not set in mode, the array is assumed to contain no data, and characters are stored beginning at ptr. Seeks are permitted within the range of the array.


strstream::rdbuf

Header

strstream.h

Prototype

strstreambuf *strstream::rdbuf();

Description

This function returns a pointer to the strstreambuf associated with strstream. It works like its counterparts in the base classes, except its return type is specifically a strstreambuf*.

strstream::str

Header

strstream.h

Prototype

strstream::str

Description

This function returns a pointer to the start of the underlying array, and freezes (see class strstreambuf) the stream. If the array was dynamically allocated, it is not automatically deleted, and is no longer expandable (see strstreambuf::freeze).

Until str() is called, a dynamically allocated array is automatically freed when the streambuf is destroyed. After a call to str(), the programmer is responsible for freeing the array.


Class strstreambuf

The strstreambuf class is derived from streambuf, specialized for memory-based (string-based) streams. A strstreambuf object uses a char array (string) as the source or destination of characters. Characters are fetched (input) from the array and consumed by (written to) the array. Unlike filebufs, strstreambuf provides storage but does not coordinate activity between the stream and the ultimate source and destination.

Class streambuf defines the basic streambuf operations that strstreambuf uses. Pointers get and put point to the attached array; moving these pointer corresponds to incrementing or decrementing a char*.

Memory based stream classes strstream, istrstream, and ostrstream use strstreambuf for stream memory operations.

strstreambuf Modes

A strstreambuf can be in one of two modes: dynamic or static. In dynamic mode, the source/destination array is automatically allocated and expanded as needed to accomodate strings of any length. When more space is needed, a new reserve area is allocated and data from the old array are copied to it; the old array is deleted.

In static mode, an array of fixed size that is allocated by the programmer is used. This array cannot be moved or changed to a new buffer, and is not deleted automatically.

A dynamic strstreambuf can be frozen (made non-expandable). A frozen or static strstreambuf can be converted to a char* for use in expressions that require C-style strings. A frozen dynamic strstreambuf can be unfrozen (made expandable again).

Member Functions of strstreambuf

Class strstreambuf is derived from streambuf, so you can use all the streambuf member functions on strstreambuf objects. The following functions are members of class strstreambuf.

strstreambuf constructors

Header

strstream.h

Prototype

strstreambuf();
strstreambuf(int n);
strstreambuf(void* (*alloc)(long), void (*del) (void*));
strstreambuf(char* ptr, int len, char* putp = 0);

Description

strstreambuf() constructs an empty, dynamic, unfrozen strstreambuf object. Space for the string is allocated automatically as needed. If you know that some minimum number of characters will be inserted, you can avoid repeated allocation and deallocation of small arrays by either creating the buffer with constructor strstream::strstream(int) or using strstream::setbuf().

strstreambuf(n) constructs an empty, dynamic, unfrozen strstreambuf object, with an initial buffer size of at least n bytes.

strstreambuf(alloc, del) constructs an empty, dynamic, unfrozen strstreambuf object. Space for the string will be allocated automatically as needed. Rather than using new and delete, the programmer supplied functions alloc and del will be called. Function alloc must take a long parameter, the number of bytes to allocate; it must return a pointer to the allocated space (of type void*), or zero on failure. If alloc is null, new will be used. Function del must take a parameter of type void*, which will be a pointer value acquired from alloc; its return type is void. If del is null, delete will be used. When using this constructor, make sure alloc and del are compatible.

strstreambuf(ptr, len, putp) constructs a static strstreambuf using the buffer pointed to by ptr. If len is positive the buffer is assumed to be len bytes in size, and operations will remain in that buffer area. If len is zero, ptr is assumed to point to a null-terminated string, and the area up to but not including the null byte will be used for the buffer. If len is negative, the buffer is assumed to be of unlimited length (a potentially dangerous mode). The get pointer will be initially set to ptr. The put pointer will be initially set to putp. If putp is not null, the initial get area will run from ptr to putp. If putp is null, stores will be treated as errors, and the initial get area will be the entire buffer.

Example

Creates a buffer consisting of the supplied text without overwriting or expanding the data:
strstreambuf greeting("Hello, world!", 0, 0);
Creates a buffer consisting of the supplied text; the data can be over-written from 'w' through '! ', but not expanded:
char *hi = "Hello, world!";
strstreambuf greeting(hi, 0, hi + 7);
Creates a buffer consisting of the supplied text. The "Hello" portion of the data can be read or overwritten; the remainder of the buffer is inaccesable:
char *hi = "Hello, world!";
strstreambuf greeting(hi, 5, hi);

strstreambuf::freeze

Header

strstream.h

Prototype

strstreambuf::freeze(int i = 1);

Description

If i is non-zero, this function freezes the dynamic buffer. If i is zero, it unfreezes the buffer. Freezing prevents automatic deletion of the buffer, even when the strstreambuf is destroyed. It also prevents expansion of the buffer beyond its current size.

Typically, you freeze a buffer to permit taking a pointer to it that remains reliable until the buffer is explicitly unfrozen. Once unfrozen, a dynamic buffer can be automatically expanded and deleted. Freezing is irrelevant for a static buffer, since it is never automatically expanded or deleted.


strstreambuf::setbuf

Header

strstream.h

Prototype

streambuf *strstreambuf::setbuf(char *ptr, int len);

Description

If ptr is null, the value of len is saved, and the next dynamic mode buffer allocation will be at least len bytes. (This applies only to the next allocation; the value of len is then discarded.) The function returns a pointer to a strstreambuf, or nothing if ptr is not null.

If ptr is not null, the request is ignored; replacing the buffer of any static or dynamic strstreambuf is not possible.

Typically, use this function to force a suitably large allocation when a buffer was going to be expanded, avoiding potentially many small allocation and deallocation sequences.


strstreambuf::str

Header

strstream.h

Prototype

char *strstreambuf::str();

Description

This function freezes ssbuf and returns a pointer to the beginning of the buffer. If ssbuf is in dynamic mode but the buffer is empty, the returned pointer might be null.
Home | Compiler & Tools | IDDE Reference | STL | Search | Download | Forums