File I/O Basics
Most projects in this course will require you to read numeric
and/or text data from a file. We will not be reading binary files.
- When your program takes input from a file, it is said to
be "reading" the file.
- When your file sends output to
a file, it is said to be "writing" to the file.
- We will assume that we are reading from the beginning to the
end of the file, so we will not be "backing up" in the file to read
data a second time.
- Similarly, we will be writing to a file from beginning to end
without "backing up".
- To perform file I/O your program must #include <fstream>.
Connecting a stream to a file
Before your program can read from a file or write to a file, it must first make
a "connection" between the file and a stream. An ifstream
is used for file input and an ofstream is used for file output.
To create a stream, simply declare a variable of the appropriate type.
ifstream inStream;
ofstream outStream;
Having created the stream, your program must now connect the stream
to the file and open the file. Your program should check
that the file was opened successfully and exit() if opening the file fails.
inStream.open( "infile.txt" );
if (inStream.fail( ) )
{
cout << "Error opening infile.txt" << endl;
exit( -1 );
}
// ---- OR -----
inStream.open( "infile.txt" );
if (! inStream )
{
cout << "Error opening infile.txt" << endl;
exit( -1 );
}
Note that the parameter for open( ) is a C-style string and
not a C++ string. This allows us to pass a command line argument directly
to open( ) as in this code snippet
int main ( int arc, char *argv[ ])
{
ifstream inStream;
inStream.open( argv[ 1 ] );
// the rest of main
}
It also means that if our filename is stored in a C++ string,
we must "convert" it to a C-style string using
string's c_str( ) function
as in the code snippet below
string filename = "test.dat";
inStream.open( filename.c_str( ) );
Closing a stream
Once your program has completed all input or output to/from the file,
it is good programming practice to close the file. If you fail to
close the file, the operating system will do so for you if your program
teminates normally. If your program aborts, the state of the file is
undefined.
inStream.close( );
Last Modified: Monday, 28-Aug-2006 10:15:54 EDT