#include #include #include using namespace std; const unsigned MaxRecLen = 80; const unsigned MaxFileName = 200; int main() { ifstream if1, if2; ofstream of; char infile1[ MaxFileName + 1 ], infile2[ MaxFileName + 1 ], outfile[ MaxFileName + 1 ]; char rec1[ MaxRecLen ], rec2[ MaxRecLen ]; // Prompt for and read file names. cout << "Input file 1: "; cin >> infile1; cout << "Input file 2: "; cin >> infile2; cout << "Output file: "; cin >> outfile; // Open the files. if1.open( infile1 ); if2.open( infile2 ); of.open( outfile ); // Merge the files until both are empty. An empty record // is one whose length as a string is zero. We assume // that records are terminated by a newline character // and that the input files are sorted. //*** loop prolog if1.getline( rec1, MaxRecLen ); if2.getline( rec2, MaxRecLen ); //*** While both input files still contain records, // compare the records and output the one // that lexicographically precedes the other. while ( strlen( rec1 ) && strlen( rec2 ) ) { // if rec1 < rec2, output rec1 and get another if ( strcmp( rec1, rec2 ) < 0 ) { of << rec1 << endl; if1.getline( rec1, MaxRecLen ); } // rec2 <= rec1, so output rec2 and get another else { of << rec2 << endl; if2.getline( rec2, MaxRecLen ); } } //*** If the first file still contains records but the // the second does not, output the remaining records // from the first file. while ( strlen( rec1 ) ) { of << rec1 << endl; if1.getline( rec1, MaxRecLen ); } //*** If the second file still contains records but the // first does not, output the remaining records from // the second file. while ( strlen( rec2 ) ) { of << rec2 << endl; if2.getline( rec2, MaxRecLen ); } // Close the input and output files and exit. if1.close(); if2.close(); of.close(); return 0; }