Up to this point we have only dealt with the i/o streams cin and cout. A program can create its own i/o stream, called a file stream, that can be associated with a file.
To use a file stream:
include <iostream> and <fstream>
Create the stream:
For input: ifstream in_stream_name; For output: ofstream out_stream_name;
Open the stream:
stream_name.open( fileName ); stream_name.open( fileName, ios::binary);
There is a possibility that the open operation could fail. As before, the name of the stream can be used as a boolean expression to test for a successful open.
The easiest way to do this is by using the assert() function, which is included in the <cassert> library.
ifstream infile; infile.open("input.txt"); assert(infile);
Once a stream is open, it may be used the same way as cin and cout.
int i; ifstream infile; ofstream outfile; infile.open("input.txt"); assert(infile); outfile.open("output.txt"); assert(outfile); infile >> i; outfile << "The value of i is" << setw(4) << i << endl;
With the exception of reading from a file with binary data. In C, fread() was used. In C++, we will use the read() function. The format for this is:
read ((char *) &buf, size); &buf -- is the address of where the data should be stored size -- the number of bytes to be read (think about using sizeof(buf))
There are a few different ways to test for end of file:
1. infile >> i; while (infile) while ( infile >> i ) { outfile << "i = " << i << endl; outfile << "i = " << i << endl; infile >> i; } 2. infile >> i; while ( !infile.eof() ) { outfile << "i = " << i << endl; infile >> i; }
Once processing of the stream is complete, it should be closed.
infile.close(); outfile.close();
After a program has been compiled and linked, it can be run via i/o redirection so that data can be read from and written to files.
An input file will be read from as if a user was typing values in via a keyboard.
lx% ./executable_file_name < input_file_name lx% ./executable_file_name > output_file_name lx% ./executable_file_name < input_file_name > output_file_name