- cout and cin are objects
- To create file stream objects, we need to include the
<fstream> library:
#include <fstream>
using namespace std;
- This library has classes ofstream ("output file stream")
and ifstream ("input file stream"). Use these to
declare file stream objects:
ofstream out1, bob; // create file output streams, called out1 and bob
ifstream in1, joe; // create file input streams, called in1 and joe
- File stream objects need to be attached to files before they can be
used. Do this with a member function called open,
which takes in the filename as an argument:
out1.open("outfile1.txt"); // for ofstreams, these calls create
bob.open("clients.dat"); // brand new files for output
in1.open("infile1.txt"); // for ifstreams, these calls try to open
joe.open("clients.dat"); // existings files for input
- Will open() always work?
- For an input file, what if the file doesn't exist? doesn't have read
permission?
- For an output file, what if the directory is not writable? What if
it's an illegal file name?
- Since it's possible for open() to fail, one should always
check to make sure there's a valid file attached
- When finished with a file, it can be detached from the stream object
with the member function close():
in1.close();
out1.close();
bob.close();
Note that the close function simply closes the file. It does not
get rid of the stream object. The stream object can now be used to attach
to another file, if desired:
in1.open("infile2.txt");