C++ provides the iostream interface in addition to the standard I/O library. It is the oldest part of the standard library. The opening of files involves use of an additional class fstream and will be described later.
Three pre-opened streams exist, cin, cout and cerr
corresponding to standard input, output and error. The 3 streams
are objects and there are many member functions for formatted input
and output but most do not usually need using directly because
the stream operators: ``>>'' for input, and
``<<'' for output cope with most problems.
The basic use of these operators has already been described.
File I/O is very simple using streams. There are classes to represent files to be read: ifstream and for files for writing: ofstream. Their definitions are in fstream.h Here is a very simple program that takes 2 file names as arguments and copies the first file to the second.
#include <cstdlib>
#include <iostream.h>
#include <fstream.h>
int main(int argc, char *argv[]) {
char ch;
if(argc != 3) {
cerr << " must have 2 filenames\n"; exit(1);
}
ifstream inFile(argv[1]);
if(inFile.fail()) {
cerr << "cant open " << argv[1] << "\n"; exit(1);
}
ofstream outFile(argv[2]);
if(outFile.fail()) {
cerr << "cant open " << argv[2] << "\n"; exit(1);
}
while(inFile.get(ch)) outFile.put(ch);
}
Comments on the preceding program:
rabbit(279)$ a.out scores.dat new.dat
ifstream inf("testing.dat");
ifstream inf;
...
inf.open("testing.dat");
.
The stream operators can be overloaded for class objects, but
because of the asymmetry of member operators and because
>> and << are stream members with a stream
as left argument they cannot be of
overloaded members of user-defined classes.
In the case of output for List objects
the « operator can be defined outside and use
an Iterator:
ostream &operator <<(ostream &s, const List &l) {
Iterator i(l);
s << "[";
for(Iterator i(l); ! i.done(); i.step())
s << "," << i.get();
s << "]";
return s;
}
Then the expression: cout << a where a is an List
will output all the elements of a enclosed in [..]
and separated by commas.
Notice also that the ``<<'' operator returns an ostream &
result, this is so that it can be used in expressions and the operation
will return the stream that can then be used by the next ``<<''
operation.
© University of Hertfordshire Higher Education Corporation (1998)