We're always interested in getting feedback. E-mail us if you like
this guide, if you think that important material is omitted, if you
encounter errors in the code examples or in the documentation, if you
find any typos, or generally just if you feel like e-mailing. Mail to
Frank Brokken
or use an
e-mail form.
Please state the concerned document version, found in
the title. If you're interested in a printable
PostScript copy, use the
form, or
better yet,
pick up your own copy by ftp
from ftp.icce.rug.nl/pub/http.
Earlier (in sections 3 and 9) we've already seen examples of the use of the C++ I/O library. In this chapter we'll cover the library to a larger extent.
Apart from defining the insertion (<<) and extraction(>>) operators,
the use of the C++ I/O library offers the additional advantage
of type safety in all kinds of standard situations. Objects (or plain
values) are inserted into the iostreams. Compare this to the situation
commonly encountered in C where the fprintf()
) function is used to
indicate by a format string what kind of value to expect where. Compared to
this latter situation C++'s iostream approach uses the objects where
their values should appear, as in
cout << "There were " << nMaidens << " virgins present\n";
The compiler notices the type of the nMaidens
variable, inserting
its proper value at the appropriate place in the sentence inserted into
the cout
iostream.
Compare this to the situation encountered in C. Although C compilers
are getting smarter and smarter over the years, and although a well-designed
C compiler may warn you for a mismatch between a format specifier and the
type of a variable encountered in the corresponding position of the argument
list of a printf()
statement, it can't do much more than warn you.
The type safety seen in C++ prevents you from making type
mismatches, as there are no types to match.
Apart from this, the iostreams offer more or less the same set of possibilities as the standard streams of C: files can be opened, closed, positioned, read, written, etc.. The remainder of this chapter presents an overview.
In general, input is managed by istream
objects, having the derived
classes ifstream
for files, and istrstream
for strings (character
arrays), whereas
output is mangaged by ostream
objects, having the derived classes
ofstream
for files and ostrstream
for strings.
If a file should allow both reading from and writing to, a fstream
object
should be used.
Finally, in order to use the iostream
facilities, the header file
iostream.h
must be included in source files using these facilities.
<<
) points to the ostream
object wherein
the information is inserted. The extraction operator points to the
object receiving the information obtained from the istream
object.
As an example, the <<
operator as defined with the class ostream
is an overloaded operator having as prototype, e.g.,
ostream &ostream::operator <<(char const *text)
The normal associativity of the <<
-operator remains unaltered, so
when a statement like
cout << "hello "
), and a ostream &
object, which is actually the
same cout
object. From here, the statement is reduced to
cout
.
Since the <<
operator has a lot of (overloaded) variants, many types of
variables can be inserted into ostream
objects. There is an overloaded
<<
-operator expecting an int
, a double
, a pointer, etc. etc..
For every part of the information that is inserted into the stream the operator
returns the ostream
object into which the information so far was inserted,
and the next part of the information to be inserted is devoured.
As we have seen in the discussion of friends, even new classes can
contain an overloaded <<
operator to be used with ostream
objects
(see sections 9.2 and 9.3).
Consider the following code example:
This is a bit unexpected. How to get the addresses? By using an explicit
cast to the generic pointer void *
the problem is solved:
The above code produces, e.g.,
scanf()
function. I.e., white-space characters are skipped. Also,
the operator doesn't expect pointers to variables to be given new values, but
references (with the exception of the char *
).
Consider the following code:
This example shows several characteristics of the extraction operator worth noting. Assume the input consists of the following lines:
i1
and i2
.
White-space (newlines, spaces, tabs) is skipped, and the values
125 and 22 are assigned to i1
and i2
.
If the assignment fails, e.g., when there are no numbers to be converted, the result of the extraction operator evaluates to a zero result, which can be used for testing purposes, as in:
if (!(cin >> i1))
hello
and world
are
returned, but the blanks that appear in between are not returned.
Furthermore, the final '.'
is not returned, since that one's
used as a sentinel: the delimiter to end the while
-loop, when the
extraction is still successful.
char *
is passed, white-space
delimited strings are extracted. So, here the words this, example,
shows, that, we're, not, yet, done, with
and C++
are returned.
Then, the end of the information is reached. This has two consequences:
First, the while
-loop terminates. Second, an empty string is
copied into the buffer
variable.
stdin
, the standard input
stream, normally connected to the keyboard, stdout
, the (buffered) standard
output stream, normally connected to the screen, and stderr
, the
(unbuffered) standard error stream, normally not redirected, and als connected
to the screen.
In C++ comparable iostreams are
cin
, an istream object from which information can be
extracted. This stream is normally connected to the keyboard.
cout
, an ostream
object, into which information can be
inserted. This stream is normally connected to the screen.
cerr
, an ostream
object, into which information can be
inserted. This stream is normally connected to the screen. Insertions
into that stream are unbuffered.
clog
, an ostream
object, comparable to cerr
, but using
buffered insertions. Again, this stream is normally connected to the
screen.
iostream.h
and fstream.h
. Files to read are accessed through
ifstream
objects, files to write are accessed through ofstream
objects.
Files may be accessed for reading and writing as well. The general fstream
object is used for that purpose.
Apart from the iostream.h
header file the headerfile fstream.h
must be
included when an fstream, ofstream,
or ifstream
object must be
constructed or used.
ofstream
object must be created,
the constructor receiving the name of the file to be opened:
ofstream out("outfile");
By default this will result in the creation of the file, and information
inserted into it will be written from the beginning of the file. Actually,
this corresponds to the creation of the ofstream
object in standard output
mode, for which the enumeration value ios::out
could have been provided as
well:
ofstream out("outfile", ios::out);
Alternatively, instead of (re)writing the file, the ofstream
object could be
created in the append mode, using the ios::app
mode indicator:
ofstream out("outfile", ios::app);
Normally, information will be inserted into the ofstream
object using the
insertion operator <<
, in the way it is used with the standard streams
like cout
, e.g.:
out << "Information inserted into the 'out' stream\n";
Just like the fopen()
function of C may fail, the construction of the
ofstream
object might not succeed. When an attempt is made to
create an ofstream
object, it is a good idea to test the successful
construction. The ofstream
object returns 0 if its construction failed.
This value can be used in tests, and the code can throw an exception (see
section 13) or it can handle the failure itself, as in the
following code:
ifstream
object must be created,
the constructor receiving the name of the file to be opened:
ifstream in("infile");
By default this will result in the opening of the file for reading. The file
must exist for the ifstream
object construction to succeed.
Instead of the shorthand form to open a file for reading, and explicit ios
flag may be used as well:
ifstream in("infile", ios::in);
Normally, information will be extracted from the ifstream
object using the
extraction operator >>
, in the way it is used with the standard stream
cin
, e.g.:
cin >> x >> y;
The extraction operator skips blanks: between words, between characters, between numbers, etc.. Consequently, if the input consists of the following information:
12
and 13
into x
and y
,
will then return the character a
and b
, and will finally read hello
and world
into the character array buffer
:
int
s, white space delimited strings for char []
s,
etc..
Just like the fopen()
function of C may fail, the construction of the
ifstream
object might not succeed. When an attempt is made to
create an ifstream
object, it is a good idea to test the successful
construction. The ifstream
object returns 0 if its construction failed.
This value can be used in tests, and the code can throw an exception (see
section 13) or it can handle the failure itself, as in the
following code:
fstream
object
must be created. Again, the constructor receives the name of the file to be
opened:
fstream inout("infile", ios::in | ios::out);
Note the use of the ios
constantst ios::in
and ios::out
, indicating
that the file must be opened both for reading and writing. Multiple mode
indicators may be used, concatenated by the binary or operator '|'
.
Alternatively, instead of ios::out
,
ios::app
might have been used, in which case writing will always be done
at the end of the file.
With fstream
objects, the ios::out
will result in the creation
of the file, if the file doesn't exist, and if ios::out
is the only
mode specification of the file. If the mode ios::in
is given as well,
then the file is created only if it doesn't exist. So, we have the following
possibilities:
Once a file has been opened in read and write mode, the <<
operator
may be used to write to the file, while the >>
operator may be used
to read from the file. These operations may be performed in random order.
The following fragment will read a blank-delimited word from the file,
will write a string to the file, just beyond the point where the string
just read terminated, and will read another string: just beyond the location
where the string just written ended:
<<
and >>
can apparently be used with fstream
objects, you might wonder whether a series of <<
and >>
operators
in one statement might be possible. After all, f >> buffer
should produce
a fstream &
, shouldn't it?
The answer is: it doesn't. The compiler casts the ftream
object into
an ifstream
object in combination with the extraction operator, and into an
ofstream
object in combination with the insertion operator. Consequently,
a statement like
f >> buffer << "grandpa" >> buffer;
no match for `operator <<(class istream, char[8])'
istream
class, the fstream
object is apparently considered an ifstream
object in combination with
the extraction operator.
Of course, random insertions and extractions are hardly used. Generally,
insertions and extractions take place at specfic locations in the file.
In those cases, the position where the insertion or extraction must take
place can be controlled and monitored by the seekg()
and tellg()
memberfunctions. The memberfunction seekg()
expects two arguments,
the second one having a default value:
seekg(long offset, seek_dir position = ios::beg);
long
offset with respect to a seek_dir
postion.
The seek_dir
position may be one of:
ios::beg
: add offset
to the begin of file position. Negative
offsets result in an error condition, which must be cleared before
any further operations on the file will succeed.
ios::end
: add offset
to the end of file position. Positive
offsets result in the insertion of as many padding (char)0
characters as necessary to reach the intended offset.
ios::cur
: add offset
to the current file position. If adding
the offset
to the current position would result in a position
before ios::beg
, then, again, an error condition results. If the
position would be beyond ios::end
, then extra (char)0
characters are supplied.
Error conditions (see also section 12.3.4) occurring
due to, e.g., reading beyond end of file, reaching end of file, or positioning
before begin of file, can be cleared using the clear()
memberfunction.
Following clear()
processing continues. E.g.,
Several condition member functions of the fstreams
exist to manipulate
the states of the stream:
bad()
: this member function returns a non-zero value when an invalid
operation has been requested, like seeking before the begin of file
position.
eof()
: this member function returns a non-zero value when the stream
has reached EOF
.
fail()
: this member function returns a non-zero value when
eof()
or bad()
returns a non-zero value.
good()
, on the other hand,
returns a non-zero value when there are no error conditions. Alternatively,
the operator '!'
could be used for that in combination with fail()
. So
good()
and !fail()
return identical logical values.
A subtlety is the following: Assume a stream is constructed, but not attached
to an actual file. E.g., the statement ifstream instream
creates the
stream object, but doesn't assign it to a file. However, if we next
check it's status through good()
this member will return a non-zero value.
The `good' status here indicates that the stream object has been cleanly
constructed. It doesn't mean the file is also open. A direct test for that
can be performed by inspecting instream.rdbuf()->is_open
. If non-zero,
the stream is open.
When an error condition has occurred (i.e., fail()
returns a non-zero
value), and can be repaired, then the member
function clear()
should be called to clear the error status of the file.
stream
objects
which are worth while mentioning.
gcount()
: this function returns the number of characters read by
getline()
(described below) or read()
(described below).
flush()
: this function flushed the output of the ostream
object.
get()
: returns the next character as an int
: End-of-file is
returned as EOF
, a value which can't be a character.
get(char c)
: this function reads a char
from an istream
object, and returns the istream
object for which the function
was called.get()
and get(char c)
functions read separate characters,
and will not skip whitespace.
getline(char *buffer, int size, int delimiter = '\n')
:
this function
reads up to size - 1
characters or until delimiter
was read
into buffer
, and appends a final ascii-z
. The delimiter is not
entered into buffer
. The function changes the state of the
output-stream to fail if a line was not terminated by
the delimiter. Since this situation will prevent the function
from reading more information, the function clear
must be
called in these circumstances to allow the function to produce
more information. The frame for reading lines from an
istream
object is, therefore:
istream &ignore([int n] [, int delimiter])
. This function
skips over a certain number of characters, but not beyond the
delimiter
character. By default, the delimiter
character is EOF
: the function ignore()
will not skip
beyond EOF
. If the number of characters isn't specified,
one character will be skipped.
int peek()
. This function returns the character that will be
read with the next call to the function get()
.
istream &putback(char c)
. This function attempts to puts
character c
back into the stream. The most recently read
character character may always be returned into the stream. If
the character can't be returned, EOF
is returned. This
function is the analogon of C's ungetc()
function.
int opfx()
. This function should be called before any further
processing. If the ostream
object is in the state `good',
flush()
is called for that object, and 1 is returned. Otherwise,
0 is returned. The p
in opfx()
inidicates prefix: the
function should be called before processing the ostream
object.
int osfx()
: This function is the suffix equivalent for opfx()
.
called at the conclusion of any processing.
All the ostream
methods end by calling osfx()
. unitbuf
flag is set for this stream, osfx()
flushes any
buffered output for it, while any
output buffered for the C
output streams stdout
and stderr
files is flushed if the stdio
flag was set for this stream.
read(char *buffer, int size)
: this function reads
size
bytes from the istream
calling the function into
buffer
.
write(char const *str, int length)
: writes length
characters in
str
to the ostream
object for which it was called, and it
returns the ostream
object.
iostreams
, there
are situations in which special formatting is required. Formatting may
involve the control of the width of an output field or an input buffer
or the form (e.g., the radix) in which a value is displayed. The
function format()
can be used for special formatting,
12.3.6.1: The function format()
12.3.6.3: The function precision()