[Home]
[Search]
[Contents]
C++, like C, has no built-in input or output statements. Instead, I/O facilities are provided by a library. The standard C++ I/O library is the iostream library.
As with much of object oriented programming, iostreams can be difficult to understand without reading through the material more than once. A terminology section defines many of the basic terms.
Predefined Iostreams
The four predefined iostreams are:
The predefined iostreams are fully buffered, except for cerr. See
the "Output Using Iostreams" and "Input Using Iostreams" sections.
Basic Structure of Iostream Interaction
The iostream library allows a program to use any number of input or output streams. Each stream has some source or sink, which might be one of the following:
The ifstream, ofstream, and fstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output with files.
The istrstream, ostrstream, and strstream classes, which are derived from istream, ostream, and iostream respectively, handle input and output to and from arrays of characters.
When you want to open an input or output stream, you create an object of one of these types. You associate the streambuf member of the stream with a device or file. You generally do this association through the stream constructor, so you don't deal with the streambuf directly. The iostream library predefines stream objects for the standard input, standard output, and error output, so you don't have to create your own objects for those streams.
You use operators or iostream member functions to insert data into a stream (output) or extract data from a stream (input), and to control the format of data that you insert or extract.
To insert and extract a new data type (that is, one of your classes), you generally overload the insertion and extraction operators.
Iostream Terminology
The iostream libarary descriptions use the following terms, which are
similar to terms from general programming but with specialized
meanings.
Term/Definition
Using Iostreams
To use iostream routines, include the header files for the part of the
library you need. The header files are:
Header File/Description
Output Using Iostreams
Output using iostreams usually relies on the overloaded left shift
operator (<<) which, in the context of iostream, is called the
insertion operator. To send a value to standard output, insert the
value in the predefined output stream cout and use the insertion
operator. For example:
cout << someValue;
The insertion operator, overloaded for all built-in types, converts the
value of someValue to its correct output representation. If, for
example, someValue is a float value, the << operator converts
the value to the correct sequence of digits and includes a decimal
point. Where it inserts float values on the output stream, << is
called the float inserter. In general, given a type X, << is called the X inserter. The format of output and how to control it is discussed in
the "Format Control" section.
The iostream library does not know about user-defined types. If you
define types for output, you must define an inserter (that is, overload
the << operator) to handle them correctly.
The << operator may be applied repetitively. To insert two values on
cout, use the statement:
cout << someValue << anotherValue;
Output shows no space between the two values. To include spaces
in the output use the statement:
cout << someValue << " " << anotherValue;
The << operator has the precedence of the left shift operator (its
built-in meaning). As with other operators, you can always use
parentheses to guarantee the order of action. It is often a good idea
to use parentheses to avoid problems of precedence. Of the
following four statements, the first two are equivalent, but the last
two are not.
cout << a+ b; // + has higher precedence than <<
Defining Your Own Insertion Operator
cout << string1 << string2;
Handling Output Errors
When an error occurs, the iostream where it occurred enters an error
state. Bits in the iostream's state are set according to the general
category of the error. The inserters defined in iostream ignore
attempts to insert data into any stream that is in an error state, so
such attempts do not change the iostream's state.
In general, the recommended way to handle errors is to check the
state of the output stream periodically in some central place. If an
error exists, you should handle it in some way. This chapter assumes
that you define a function error, which takes a string and aborts
the program. error is not a predefined function. See "Handling
Input Errors" for an example of an error function. Examine the
state of an iostream with the operator !, which will return a nonzero
value if the iostream is in an error state. For example:
Binary Output
cout << (a+ b);
cout << (a& y);// << has precedence higher than &
cout << a& y;// probably an error: (cout << a) & y
The string class defined in the "Sample Program" section has this
definition:
class string {
private:
char* data;
size_t size;
public:
(functions not relevant here)
friend ostream& operator<<(ostream&,
const string&);
friend istream& operator>>(istream&, string&);
};
The insertion and extraction operators in this case must be defined
as friends because the data part of the string class is private. The definition of operator<< overloaded for use with strings is:
ostream& operator<< (ostream& ostr,
const string& output)
{ return ostr << output. data;}
operator<< takes a reference to an ostream& as its first
argument and returns the same ostream, making it possible to
combine insertions in one statement:
Checking for errors when overloading operator<< is not necessary
because the iostream library can propagate errors.
if (! cout) error("output error");
Another way to test for errors exists. The ios class defines
operator void *() so it returns a NULL pointer when an error
occurs. This allows you to use a statement like this:
if (cout << x) return ; // return if successful
You can also use the function good, a member of ios:
if (cout. good() ) return; // return if successful
The error bits are declared the definition of class ios in the enum:
enum io_state {goodbit= 0, eofbit= 1, failbit= 2,
badbit= 4, hardfail= 0x80} ;
Flushing
As with most I/O libraries, iostream often accumulates output and
sends it on in larger and generally more efficient chunks. To flush
the buffer, simply insert the special value flush. For example:
cout << "Needs to get out immediately." << flush;
flush is a kind of object known as a manipulator, which is a value
that may be inserted into an iostream to have some effect other than
causing output of its value. It is really a function that takes an
ostream& or istream& argument and returns its argument after
performing some actions on it (see "Manipulators").
To obtain output in the raw binary form of a value, use the member
function write as:
cout. write((char*)& x, sizeof(x));
This, however, violates type discipline by converting &x to char*.
Doing so is normally harmless, but if the type of x is a class with
pointers, virtual member functions, or one that requires nontrivial
constructor actions, the value written by the above example cannot
be read back in properly.
Input Using Iostreams
Input using iostream is similar to output. Use the extraction operator
>> and string together extractions the way you can with insertions.
For example to get two values from standard input:
cin >> a >> b ;
As with other overloaded operators, the extractors used depend on
the types of a and b (and two different extractors are used if a and b
have different types). The format of input and how you can control it
is discussed in some detail in "Format Control". In general, though,
leading whitespace characters (spaces, newlines, tabs, form-feeds,
and so on) are ignored.
Defining Your Own Extraction Operators
When you want input for a new type, you overload the extraction operator for it, just as you overload the insertion operator for output.
Class string (shown in sections "Output Using Iostreams" and "Sample Program") defines its extraction operator like this:
istream& operator>> (istream& istr, string& input)
{
const int maxline = 256;
char holder[maxline];
istr. get(holder, maxline, '\n');
input = holder;
return istr;
}
By convention, an extractor converts characters from its first
argument (in this case, istream& istr), stores them in its second
argument (always a reference) and returns its first argument. The
second argument must be a reference because an extractor is meant
to store the input value in its second argument.The char* Extractor
This predefined extractor is mentioned here because it can cause
problems. You use it like this:
char x[50];
cin >> x;
The extractor skips leading whitespace and extracts characters and
copies them to x until it reaches another whitespace character. It
then completes the string with a terminating null (0) character. Be
careful because input can overflow the given array.
Reading Any Single Character
The char extractor skips whitespace, which can be a problem if
your program needs to read the next character whether or not it is
whitespace. To do this with either form of function get member:
char c;
cin. get(c); // leaves c unchanged if input fails
int b;
b = cin. get(); // sets b to EOF if input fails
To skip only blanks, stopping on a tab, newline, or any other
character:
int a;
do {
a = cin. get();
while(a == ' ' );
Binary Input
To read binary values (such as those written with the member
function write), use the read member function. To input the raw
binary form of x using the read member function, do the following,
which is the inverse of the earlier example that used write.
cin. read((char*)& x, sizeof(x));
Peeking at Input
Use the peek member function to look at the next character in the stream without extracting it. For example:
if (cin. peek() != c) return 0;
Extracting Whitespace
By default, iostream extractors skip leading whitespace. You can turn off the skip flag to prevent this from happening. The following code turns off whitespace skipping from cin, then turns it on again.
cin. unsetf(ios::skipws); // turn off . . .
cin. setf(ios::skipws, ios::skipws); // turn on
You can use the iostream manipulator ws to remove leading
whitespace from the iostream, whether or not skipping is enabled.
To remove the leading whitespace from iostream istr:
istr >> ws;
Handling Input Errors
By convention, an extractor whose first argument has a nonzero error state should not extract anything from the input stream and should not clear any error bits. An extractor that fails should set at least one error bit.
As with output errors, you should check the error state periodically
and take some action (such as aborting) when you find a nonzero
state. The ! operator returns the error state of an iostream. For
example, the following code produces an input error if you type
alphabetic characters for input:
#include <stream.h>
#include <stdlib.h>
void error (const char* message) {
cout << message << "\n" ;
exit(1);
}
main() {
cout << "Enter some characters: ";
int bad;
cin >> bad;
if (! cin) error(" aborted due to input error");
cout << "If you see this, not an error." <<
"\n";
return 0;
}
Class ios has member functions that you can use for error handling.
See the next chapter.
Using Iostreams with stdio
You can use stdio with C++ programs, but problems can occur
when you mix iostreams and stdio in the same standard stream
within a program. For example, if you write to both stdout and
cout, independent buffering will occur; results might not be what
you expect. The problem is worse if you input from both stdin and
cin, since independent buffering can turn the input into trash.
To eliminate this problem with standard input, standard output, and
standard error, use the following instruction before performing any
input or output. It connects all the predefined iostreams with the
corresponding predefined stdio FILEs.
ios::sync_with_stdio();
Such a connection is not the default because a significant
performance penalty occurs when the predefined streams are made
unbuffered as part of the connection. You can use both stdio and
iostreams in the same program applied to different files with no
difficulty. That is, you can write to stdout using stdio routines
and write to other files attached to iostreams. You can open stdio
FILEs for input and also read from cin so long as you do not also
try to read from stdin.
Creating Iostreams
To read or write a stream other than the predefined iostreams, you must create your own iostream. In general that means creating objects of types defined in the iostream library. The following sections discuss the various types available.
Dealing with Files Using Class fstream
Dealing with files is similar to dealing with standard input and
standard output; classes ifstream, ofstream, and fstream are
derived from classes istream, ostream and iostream,
respectively. As derived classes, they inherit the insertion and
extraction operations (along with the other member functions) and
also have members and constructors for use with files.
You must include the file fstream.h to use any of the fstreams.
Use an ifstream when you only want to perform input, an
ofstream for output only, and an fstream for a stream on which
you want to perform both input and output. Use the name of the file
as the constructor argument.
For example, to copy the file thisFile to the file thatFile:
Open Mode
Repositioning Within a File
enum seek_dir {beg= 0, cur= 1, end= 2 }
ifstream fromFile(" thisFile");
if (! fromFile)
error(" unable to open 'thisFile' for input");
ofstream toFile (" thatFile");
if (!toFile )
error(" unable to open 'thatFile' for output");
char c ;
while (toFile && fromFile. get(c)) toFile. put(c);
This code:
Note
You would not really copy a file this way, one
character at a time. This code is provided only as an
example of using fstreams. Instead, insert the
streambuf associated with the input stream into
the output stream.
The mode is constructed by or-ing bits from the enumerated type
open_mode, which is an public type of class ios and has the
definition:
enum open_mode {in= 1, out= 2, ate= 4, app= 8,
trunc= 0x10, nocreate= 0x20, noreplace= 0x40};
You can open a file for both input and output. For example, the
following code opens file someName for both input and output,
attaching it to the fstream variable inoutFile.
fstream inoutFile("someName", ios::in | ios::out);
Declaring an fstream Without Specifying a File
You can declare an fstream without specifying a file and open the
file later. For example, to create the ofstream toFile for writing.
ofstream toFile;
toFile.open(argv[1], ios::out);
Opening and Closing Files
You can close the fstream and then open it with another file. For
example, to process a list of files provided on the command line:
ifstream infile;
for (char** f = &argv[1]; *f; ++f)
{
infile.open(*f, ios::in);
...;
infile.close();
}
Opening a File Using a File Descriptor
If you know a file descriptor (such as the integer 1 for standard
output), you can open it like this:
ofstream outfile;
outfile. attach(1);
When you open a file by providing its name to one of the fstream
constructors or by using the open function, the file automatically
closes when the fstream is destroyed (by a delete or when it goes
out of scope). When you attach a file to an fstream, it does not
automatically close.
Several tools can alter the reading and writing position in a file.
For example, given an fstream aFile:
streampos original = aFile.tellp(); // save current position
aFile.seekp(0, ios::end); // reposition to end of file
aFile << x; // write a value to file
aFile.seekp(original); // return to original position
seekg (seekp) can take one or two parameters. When it has two
parameters, the first is a position relative to the position indicated by
the seek_dir value given as the second parameter. For example, to
move 10 bytes from the end:
aFile.seekp(-10, ios::end);
To move 10 bytes forward from the current position:
aFile.seekp(10, ios::cur);
Note
Arbitrary seeking on text streams is not portable.
Assigning Iostreams
Earlier versions of C++ allowed assignment of one stream to another.
This is no longer allowed.
The problem with copying a stream object is that when two versions
of the state information exist (such as a pointer to the current write
point within an output file) each might be changed independently.
This can cause problems. Copying stream objects is usually not
necessary.
Format Control
Format control is described in the next chapter.
Manipulators
A manipulator is a value you can insert into or extract from iostreams
to have special effects.
Because manipulators are ordinary identifiers, and therefore use up
possible names, iostream does not define them for every possible
function. Manipulators are listed and described in the next chapter.
To use predefined manipulators, include header file iomanip.h in
your program.
You can define your own manipulators. The two basic kinds of
manipulators are:
Plain Manipulators
A plain manipulator is a function that
An example of a tab manipulator that inserts a tab in an ostream:
The shift operators taking (a pointer to) such a function are
predefined for iostreams, so the function may be put in a sequence
of input or output operators. The shift operator calls the function
rather than trying to read or write a value.
ostream& tab(ostream& os) {
return os << '\t' ;
}
...
cout << x << tab << y ;
This is an elaborate way to achieve what could be done with:
const char tab = '\t';
...
cout << x << tab << y;
Here is another example, which cannot be accomplished with a
simple constant. Suppose you want to turn whitespace skipping on
and off for an input stream. You can use separate calls to
ios::setf and ios::unsetf to turn the skipws flag on and off,
or you could define two manipulators:
ostream& skipon(istream &is) {
is. setf(ios::skipws, ios::skipws);
return is;
}
ostream& skipoff(istream& is) {
is. unsetf(ios::skipws);
return is;
}
...
cin >> skipon >> x >> skipoff >> y;
Parameterized Manipulators
A parameterized manipulator takes one or more parameters. It:
The applicator calls the manipulator. The applicator is a global
function, and you make a prototype for it available in a header file.
Usually the manipulator is a static function in the file containing the
source code for the applicator. The manipulator is called only by the
applicator. If you make it static, its name stays out of the global
address space.
Several classes are defined in the header file iomanip.h. Each class
holds the address of a manipulator function and the value of one
parameter. Chapter 27, "Iostream Library Class Descriptions,"
describes iomanip classes. The previous example uses the
smanip_int class, which works with an ios. Because it works
with an ios, it also works with an istream and an ostream. The
previous example also uses a second parameter of type int.
The applicator creates and returns a class object. In the previous
code example the class object is an smanip_int, and it contains
the manipulator and the int argument to the applicator. The
iomanip.h file defines the shift operators for this class. When the
applicator function setfill appears in a sequence of input or
output operations, the applicator function is called, and it returns a
class. The shift operator acts on the class to call the manipulator
function with its parameter value, which was stored in the class.
In the next code example, the manipulator print_hex does the
following:
1. Puts the output stream into the hex mode.
2. Inserts a long value into the stream.
3. Restores the conversion mode of the stream.
The class omanip_long is used because this code example is for
output only, and it operates on a long rather than an int.
One of the parameterized manipulators in iomanip.h is setfill.
setfill sets the character that fills out field widths. It is
implemented as:
// file setfill.cpp
#include <iostream.h>
#include <iomanip.h>
// the private manipulator
static ios& sfill(ios& i, int f) {
i.fill((char) f);
return i;
}
// the public applicator
smanip_int setfill(int f) {
return smanip_int(sfill, f);
}
A parameterized manipulator is implemeted in two parts:
The manipulator looks like any other manipulator, except it takes an
extra parameter. In the previous code example, it takes an extra int
parameter. You cannot place this manipulator function in a sequence
of input or output operations, since no shift operator is defined for it.
Instead, you must use an auxiliary function- the applicator.
static ostream& xfield(ostream& os, long v)
{
long save = os. setf(ios::hex, ios::basefield);
os << v;
is. setf(save, ios::basefield);
return s;
}
omanip_long print_hex(long v)
{
return omanip_long(xfield, v);
}
strstreams: Iostreams for Arrays
See strstream in the next chapter.
stdiobufs: Iostreams for stdio FILEs
See stdiobuf in the next chapter.
Streambufs
Iostreams are the formatting part of a two-part (input or output)
system. The other part of the system is made up of streambufs,
which deal in input or output of unformatted streams of characters.
You usually use streambufs through iostreams, so you don't have to
worry about the details of streambufs. You can use streambufs
directly if you choose to, for example, if you need to improve
efficiency or to get around the error handling or formatting built in to
iostreams.
How Streambufs Work
A streambuf consists of a stream or sequence of characters and one
or two pointers into that sequence. Each pointer points between two
characters. (Pointers cannot actually point between characters, but it
is helpful to think of them that way.)
° One is a put pointer, which points just before the position
of the next character delivered.
° The other is a get pointer, which points just before the
next character that will be fetched.
A streambuf can have one or both of these pointers.
Position of Pointers
The positions of the pointers and the contents of the sequences can
be manipulated in various ways. Whether or not both pointers move
when manipulated depends on the kind of streambuf used.
Generally, with queue-like streambufs, the get and put pointers
move independently; with file-like streambufs the get and put
pointers always move together. A strstream is an example of a
queue-like stream; an fstream is an example of a file-like stream.
Using Streambufs
You never create an actual streambuf object, but only objects of
classes derived from class streambuf. Examples are filebuf and
strstreambuf, which are described in filebuf and ssbuf, in
the next chapter. You can derive your own classes from
streambuf, to provide an interface to a special device, or to
provide other than basic buffering. sbuf. pub and sbuf. prot, in
the next chapter, discuss how to do this.
Apart from creating your own special kind of streambuf, you might
want to access the streambuf associated with an iostream to get at
the public member functions. In addition, each iostream has a
defined inserter and extractor that take a streambuf pointer. When a
streambuf is inserted or extracted, the entire stream is copied.
Here is another way to copy a file, with the error checking omitted.
ifstream fromFile("thisFile");
ofstream toFile ("thatFile");
toFile << (streambuf*) fromFile. rdbuf();
Open the input and output files as before. Every iostream class has a
member function rdbuf which returns a pointer to the streambuf
object associated with it. In the case of an fstream, the streambuf
object is type filebuf. Cast the filebuf* to a streambuf* so
the appropriate inserter is called, and the entire file associated with
fromFile is copied (inserted into) the file associated with toFile.
The last line can also be written like this:
fromFile >> (streambuf*) toFile. rdbuf();
In this case, the source file is extracted into the destination. The two
methods are equivalent.
Sample Program
Here is a sample C++ program. It has a '' toy'' implementation of a string class, and a small program to test it. The class is a '' toy'' because it is not full-featured, yet it shows a number of features a real class must have.
Header file
The header file str.h for the string class string is:
/****************** str.h **********************/
/* header file str.h for toy C++ strings package
*/
#include <string.h> /* for C string functions */
class ostream; /* to declare output of strings
class string {
public:
string();
string(char *);
void append(char *);
const char* str() const;
string operator+ (const string&) const;
const string& operator=(const string&);
const string& operator=(const char*);
private:
char *data;
size_t size;
};
inline string::string() {size = 0; data = NULL;}
inline const char* string::str() const {
return data;}
ostream& operator<<(ostream&, const string&);
istream& operator>>(istream&, string&);
Implementation file
The implementation file str.cpp of the string class functions is:
The test file testr.cpp to test the string class is:
To compile and link the entire program use the command:
° Iostream classes
° Iostream functions
For an overview of Iostreams, see Chapter 26.
Note
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:
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:
°A manip part, a function taking a stream and a typ
argument and returning the stream;
°An apply part, the function invoked by the manip part,
which applies state changes or other operations.
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
Manipulator/Description
To write a parameterized manipulator:
1. Declare function manip, and then implement functions
manip and apply.
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:
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
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.
Header
fstream.h
Prototype
filebuf();
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.
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.
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.
Header
fstream.h
Prototype
int filebuf::fd();
Description
This function returns the file descriptor attached to filebuf, or
EOF if filebuf is not 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.
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.
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.
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.
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.
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.
Auxiliary class fstreambase is an implementation detail, primarily
providing a set of common functions. It is not documented.
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.
Xstream constructors
Header
fstream.h
Prototype
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.
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.
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.
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:
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.
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.
The section "Classes fstream, ifstream, and ofstream" discusses
fstream, ifstream, and ofstream together, using the notation
Xstream
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
open_mode
seek_dir
Formatting Flags
Constructors and Assignment
Class ios defines the following constructors, which are described in
the "Member Functions of ios" section.
Error States
Function/Description
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* ()
Format Control
Formatting flags can be set and cleared independent of other
operations. They change only by explicit programmer action.
Formatting Flags
Flag/Description
Format Bit Masks
Format Control Functions
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:
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.
Member Functions of ios
The following functions are members of class ios.
ios constructors
Header
iostream.h
Prototype
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:
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.
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.
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.
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());
Header
iostream.h
Prototype
int ios::eof();
Description
This function returns non-zero if the eofbit is set, and zero
otherwise.
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.
Header
iostream.h
Prototype
char ios::fill();
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".
Header
iostream.h
Prototype
long ios::flags();
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.
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.
Header
iostream.h
Prototype
long ios::iword(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
Header
iostream.h
Prototype
int ios::precision();
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.
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.
Header
iostream.h
Prototype
int ios::rdstate();
Description
This function returns the error state bits of stream ios as an int.
Header
iostream.h
Prototype
long ios::setf(long newflags);
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:
This code clears the integer conversion base to the default state:
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
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);
tie returns the current value of the tie variable.
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.
Header
iostream.h
Prototype
long ios::width();
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.
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.
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
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:
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:
Positioning Functions
These functions position the get pointer of the streambuf associated
with an istream. See the section "Class streambuf (Public Interface)"
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:
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.
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.
Header
iostream.h
Prototype
int istream::get();
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.
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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*.
The section "Classes fstream, ifstream, and ofstream" discusses
fstream, ifstream, and ofstream together, using the notation
Xstream.
Output Prefix and Suffix Functions
These functions perform setup and cleanup actions before and after
insertion operations:
Function/Description
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:
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
Unformatted Output (insertion) Functions
These functions work with unformatted output. They do not call
opfx() or osfx(). See "Member Functions of ostream".
Function/Description
Positioning Functions These functions position the put pointer of the streambuf associated
with an ostream. See the "Class streambuf (Public Interface)" section.
Function/Description
Manipulator/Description
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.
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.
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.
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.
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.
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.
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.
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.
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();
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.
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.
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*.
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.
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.
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.
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.
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 the following
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 the following
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
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.
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.
Header
streambuf::base
Prototype
char * streambuf::base();
Description
This function returns a pointer to the beginning of the reserve area.
Header
iostream.h
Prototype
int streambuf::blen();
Description
This function returns the size in chars of the reserve area, ebuf() -base().
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.
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.
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.
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.
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().
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.
streambuf::gbump(int n);
Description
This function adds n, a signed quantity, to the get pointer, without
any validity checks.
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.
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.
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.
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.
Header
iostream.h
Prototype
streambuf::pbump(int n);
Description
This function adds n, a signed quantity, to the put pointer, without
any validity checks.
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).
Header
iostream.h
Prototype
streampos streambuf::seekoff(streamoff off,
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.
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.
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.
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.
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.
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.
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.
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)".
Functions/Description
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.
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.
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.
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.
Header
iostream.h
Prototype
streampos streambuf::seekpos(streampos pos,
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
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.
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.
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.
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'.
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.
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.
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.
Header
iostream.h
Prototype
This function moves the get pointer forward one position.
Description
Use stossc in combination with sgetc (which provides
lookahead) to implement a scanner without putting back characters.
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.
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.
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*.
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 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.
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).
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.
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.
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.
/******************* str.cpp *********************/
/* implementation for toy C++ string package */
#include <iostream.h>
#include "str.h"
string::string(char *aStr)
{
if (aStr == NULL)
size = 0;
else
size = strlen(aStr);
if (size == 0)
data = NULL;
else {
data = new char [size+ 1];
strcpy(data, aStr);
}
}
void string::append(char *app)
{
size_t appsize = app ? strlen(app) :0;
char *holder = new char [size + appsize + 1];
if (size)
strcpy(holder, data);
else
holder[0] = 0;
if (app) {
strcpy(& holder[size], app);
size += appsize;
}
delete [] data;
data = holder;
}
string string::operator+(
const string& second) const
{
string temp;
temp. data = new char[size + second. size + 1]
if (size)
strcpy(temp. data, data);
else
temp. data[0] = 0;
if (second. size)
strcpy(& temp. data[size], second. data);
temp. size = size + second. size;
return temp;
}
const string& string::operator=(
const string& second)
{
if (this == &second)
return *this; /* in case string = string */
delete [] data;
if (second. size) {
data = new char[second. size+ 1];
size = second. size;
strcpy(data, second. data);
}
else {
data = NULL;
size = 0;
}
return *this;
}
const string& string::operator=(const char* str)
{
delete [] data;
if (str && str[0]) {
size = strlen(str);
data = new char[size+ 1];
strcpy(data, str);
}
else {
data = NULL;
size = 0;
}
return *this;
}
ostream& operator<< (
ostream& ostr, const string& output)
{
return ostr << output. data;
}
istream& operator>> (
istream& istr, string& input)
{
const int maxline = 256;
char holder[maxline];
istr. get(holder, maxline, '\n');
input = holder; return istr;
}
Test file
/******************* testr.cpp********************/
/* test code for toy C++ strings package */
#include <iostream.h>
#include "str.h"
main()
{
string first ("This is a string.");
cout << "first: " << first <<"\n";
string sec;
sec = first;
cout << "sec = first: " << sec << "\n";
sec = "And this is another.";
cout << "another sec: " << sec << "\n";
cout <<" Type in a string .....";
cin >> sec;
cout << "sec: "<< sec << "\n"
string third;
third = sec+ first;
cout << "sec + first: " << third << "\n";
third = sec+ sec;
cout << "sec + sec: " << third << "\n";
third. append("plus");
cout << "with append:" << third << "\n";
third = third + sec;
cout << "added to itself:" << third << "\n";
return 0;
}
Compile and link the program
sc -cpp -o testr testr.cpp str.cpp
T
his chapter contains descriptions for:
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.
you can 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
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:
The
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).
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.
Supplied file descriptors are not checked for
validity. The filebuf does not report seek failures.
filebuf(int f);
filebuf(int f, char *ptr, int len);
filebuf::attach
filebuf::close
filebuf::fd
filebuf::is_open
filebuf::open
filebuf::seekoff
filebuf::seekpos
filebuf::setbuf
filebuf::sync
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.
The following functions are members of fstream, ifstream, and
ofstream class. The notation Xstream is used to collectively
describe the member functions.
Xstream();
Xstream(int f);
Xstream(const char *name, int mode= ios::in,
int prot= filebuf::openprot);
Xstream(int f, char *ptr, int len);
Description
Xstream::attach
Xstream::close
Xstream::open
Mode/Description
Xstream::rdbuf
Xstream::setbuf
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.
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.
These enumerations are described with function fstream::open.
These enumerations are described in the section "Class streambuf
(Public Interface)", under the function streambuf::seekoff.
Member functions use these enumerations of anonymous type to
control input and output formatting. See "Format Control".
ios(sbptr)
ios() // protected
init(sbptr) // protected
ios(iosref) // private
Functions that enable testing and adjusting the error state bits, are:
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
ios defines the following format flags:
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
ios defines the following member functions for format control:
Function/Description
Function/Description
Manipulator/Description
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.
ios(streambuf* sbptr);
ios(); // protected
void init(streambuf* sbptr); // protected
ios(iosref); // private
void operator=(ios&); // private;
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.
ios:bad
ios:bitalloc
ios:clear
ios:eof
ios:fail
ios:fill
char ios::fill(char newfill);
ios:flags
long ios::flags(long newflags);
ios::good
ios:iword, ios:pword
void * ios::pword(int i);
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
int ios::precision(int newprec);
ios::rdbuf
ios:rdstate
ios:setf
long ios::setf(long newflags, long field);
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.
cout. setf(0, ios::basefield);
See the descriptions of the predefined manipulators setiosflags
and resetiosflags in the "Manipulators" section.
ios::sync_with_stdio
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
... do something ...
s. tie(oldosp);
ios:unsetf
ios:width
long ios::width(int newwidth);
ios::xalloc
Class istream
Class istream defines the behavior of input streams. It supports
formatted and unformatted extraction (input) of data from an
associated streambuf.
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:
Extractor/Description
Function/Description
Function/Description
Manipulator/Description
istream::gcount
istream::get
istream::get(char& c);
istream::get(char *ptr, int count, char delim= '\n');
istream::get(streambuf & sbuf, char delim= '\n');
istream::getline
istream::ignore
istream::ipfx
istream::peek
istream::putback
istream::read
istream::sync
Class istream_withassign
Class istream_withassign implements the assignment operator for istream objects.
Use it to redirect stream input to other streams.
istream_withassign::operator=
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.
istrstream::rdbuf
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.
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.
#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:
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.
ostream::flush
ostream::opfx
ostream::osfx
ostream::put
ostream::write
Class ostream_withassign
Class ostream_withassign implements the assignment operator for ostream objects.
Use it to redirect stream output to other streams.
ostream_withassign::operator=
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.
ostrstream(char *ptr, int len, int mode= ios::out);
ostrstream::pcount
ostrstream::rdbuf
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().
stdiobuf::stdiofile
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.
stdiostream::rdbuf
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.
Non-virtual Functions for Setting Pointers
streambuf::allocate
streambuf::base
streambuf::blen
streambuf::doallocate
streambuf::dpb
streambuf::eback
streambuf::gbumps
streambuf::egptr
streambuf::epptr
Prototype
streambuf::gptr
streambuf::overflow
streambuf::pbackfail
streambuf::pbase
streambuf::pbump
streambuf::pptr
streambuf::seekoff
ios::seek_dir dir,
int mode = (ios::in | ios::out));
streambuf::seekpos
streambuf::setbuf
streambuf::sync
streambuf::unbuffered
streambuf::underflow
Input Functions
streambuf::out_waiting
streambuf::sbumpc
streambuf::seekoff
streambuf::seekpos
int mode=(ios::in | ios::out));
streambuf::setbuf
streambuf::sgetc
streambuf::sgetn
streambuf::snextc
streambuf::sputbackc
streambuf::sputc
streambuf::sputn
streambuf::stossc();
streambuf::sync
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.
strstream::rdbuf
strstream::str
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.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.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().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.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.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.