/////////////////////////////////////////////////////// // // files.cpp // // Started 2/16/98 by Jeff Ondich // Last modified: 5/12/98 // // This program illustrates, very briefly, the // use of the ifstream class to read from a file, // and the ofstream class to write to a file. // //////////////////////////////////////////////////////// #include // Allows use of ifstream and ofstream #include // Prototypes. void InputFileExample( void ); void OutputFileExample( void ); int main( void ) { InputFileExample(); OutputFileExample(); return( 0 ); } //////////////////////////////////////////////////////// // Gets a file name from the user, reads the // words from the file and prints them, one per // line, to cout. If the file named by the user // does not exist, an error message is printed // and the program halts. //////////////////////////////////////////////////////// void InputFileExample( void ) { // Get the file name from the user. char fileName[100]; cout << "From which file would you like 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()) ) { cout << "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(); } //////////////////////////////////////////////////////// // Gets a file name from the user and writes a // foolish message into the file. If opening the // file fails, the program halts. //////////////////////////////////////////////////////// void OutputFileExample( void ) { // Get the file name from the user. char fileName[100]; cout << "To which file would you like to write? "; cin >> fileName; // Declare an ofstream object with fileName as // a constructor parameter to attempt to open // the named file. Check to make sure it // was opened successfully. ofstream myFile( fileName ); if( !(myFile.is_open()) ) { cout << "Trouble opening " << fileName << endl; exit(1); } // Write something to the file. myFile << "Nurse, I spy gypsies. Run!" << endl; myFile << "Ma, I say! Lee's as eely as I am!" << endl; myFile << "Satan, oscillate my metallic sonatas." << endl; myFile << "Go hang a salami. I'm a lasagna hog." << endl; myFile << "Flee to me, remote elf." << endl; // Clean up after yourself. myFile.close(); }