Next: Testing for end-of-file
Up: Streams and External Files
Previous: Streams
The stream must first be declared. The names for streams follow the
same rules of formation as identifiers. Thus the following
declaration declares the stream ins
for input and the stream
outs
for output:
ifstream ins; // input stream ofstream outs; // output stream
To connect these streams to the appropriate external files the
open
function is used. The open
function is a
member function of the stream class and to connect the stream
ins
to a file
indata.dat
the following statement is used:
ins.open("indata.dat");
The general form for a stream with identifier streamname and a file with name filename is:
streamname.open(
filename);
If the file indata.dat
did not exist or could not be found then
this open
function will fail. Failure of the open
function is tested by using the the function streamname.fail()
which returns true
if the open
function failed. When
using the open
function failure should always be tested for as
in the following example:
ifstream ins; ins.open("indata.dat"); if (ins.fail()) { cout << "Error opening file indata.dat" << endl; return 1; }In this example it is assumed that the failure occurs within the
main()
program. This means that the return
statement
exits the main
program and hence the program is terminated.
The value 1 that is returned indicates to the operating system that
the program has terminated with an error condition. As the main
program now returns a value it must be declared as having the type
int
rather than void
.
Having connected the external files to the streams any input/output from/to these streams will then be from/to the connected files.
In the following example two streams are declared, one for input
called ins
and another for output called outs
. These
streams are then connected to files with names indata.dat
and
results.dat
respectively by:
int main() { ifstream ins; ofstream outs; ins.open("indata.dat"); if (ins.fail()) { cout << "Error opening indata.dat" << endl; return 1; } outs.open("results.dat"); if (outs.fail()) { cout << "Error opening results.dat" << endl; return 1; } . .All access to these files now uses the declared stream names
ins
and outs
and the input/output operators <<
and >>
. Input/output manipulators can also be used on the
output stream.
Thus a data item is entered from the stream ins
by:
ins >> x;and results are output to the stream
outs
by:outs << "Result is " << setw(6) << count << endl;