|
Reference · Data types Standard C · assert.h · complex.h · ctype.h · fenv.h · float.h · locale.h · math.h · setjmp.h · signal.h · stdarg.h · stddef.h · stdio.h · stdlib.h · string.h · time.h Standard C++ · IOstream · new Win32 · gc.h DOS, DOS32, Win16 · bios.h · cerror.h · disp.h · dos.h · dos.h part 2 · emm.h · handle.h · int.h · msmouse.h · sound.h · swap.h · tsr.h · winio.h Other C · bitops.h · conio.h · controlc.h · direct.h · fltpnt.h · io.h · page.h · process.h · search.h · sys\stat.h · tabsize.h · trace.h · utime.h · unmangle.h · util.h Other C++ · regexp.h · class complex |
IOstreamThis chapter consists of:
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 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.
To use iostream routines, include the header files for the part of the
library you need. The header files are:
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
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:
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:
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:
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.
Use the peek member function to look at the next character in the stream without extracting it. For example:
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.
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:
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.
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 }
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:
A plain manipulator is a function that
An example of a tab manipulator that inserts a tab in an ostream:
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.
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 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.
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 |