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.

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