/////////////////////////////////////////////////////// // // inputFiles.cpp // // Started 2/16/98 by Jeff Ondich // Last modified: 2/16/98 // // This program illustrates, very briefly, the // use of the ifstream type to read from a file. // // Strings.h header is in /usr/include/g++ // //////////////////////////////////////////////////////// // Allows use of ifstream and ofstream #include // Allows use of gnu strings #include int main( void ) { // Get the file name from the user. char fileName[100]; cout << "What file do you want to read? "; cin >> fileName; // Declare an ifstream object with fileName as // a constructor parameter to attempt to open // the named file. Check to make sure it // was opened successfully. ifstream myFile( fileName ); if( !(myFile.is_open()) ) { cerr << "Trouble opening " << fileName << endl; exit(1); } // Read words one at a time from the file, and // print them out, one per line. Note that the // "fail()" member function of the ifstream type // is used to test for end-of-file. The end of // file is reached only after an attempt to read // past the last character. String word; myFile >> word; while( !myFile.fail() ) { cout << word << endl; myFile >> word; } // Clean up after yourself. myFile.close(); // Bye-bye. return( 0 ); }