// FILE: CopyFile.cpp // COPIES FILE IN_DATA.DAT TO FILE OUT_DATA.DAT #include // for the definition of EXIT_FAILURE // and EXIT_SUCCESS #include // required for external file streams // ASSOCIATE PROGRAM IDENTIFIERS WITH EXTERNAL FILE NAMES #define in_file "in_data.dat" #define out_file "out_data.dat" // Functions used ... // COPIES ONE LINE OF TEXT int copy_line (ifstream&, // IN: infile stream ofstream&); // OUT: outfile stream int main() { // Local data ... int line_count; // output: number of lines processed ifstream ins; // associates ins as an input stream ofstream outs; // associates outs as an output stream // Open input and output file, exit on any error. ins.open (in_file); // ins connects to file in_file if (ins.fail ()) { cerr << "*** ERROR: Cannot open " << in_file << " for input." << endl; return EXIT_FAILURE; // failure return } // end if outs.open (out_file); // outs connects to file out_file if (outs.fail ()) { cerr << "*** ERROR: Cannot open " << out_file << " for output." << endl; ins.close (); return EXIT_FAILURE; // failure return } // end if // Copy each character from in_data to out_data. line_count = 0; if (copy_line (ins, outs) != 0) line_count++; while (!ins.eof ()) if (copy_line (ins, outs) != 0) line_count++; // Display a message on the screen. cout << "Input file copied to output file." << endl; cout << line_count << " lines copied." << endl; ins.close (); // close input file stream outs.close (); // close output file stream return EXIT_SUCCESS; // successful return } // COPY ONE LINE OF TEXT FROM ONE FILE TO ANOTHER int copy_line (ifstream& ins, // IN: ins stream ofstream& outs) // OUT: outs stream // Pre: ins is opened for input and outs for output. // Post: Next line of ins is written to outs. // The last character processed from ins is ; // the last character written to outs is . // Returns: The number of characters copied. { // Local data ... const char nwln = '\n'; // newline character char next_ch; // inout: character buffer int char_count = 0; // number of characters copied // Copy all data characters from ins file stream to outs file // stream. ins.get (next_ch); while ((next_ch != nwln) && !ins.eof()) { outs.put (next_ch); char_count++; ins.get (next_ch); } // end while // If last character read was nwln write it to out_data. if (!ins.eof ()) { outs.put (nwln); char_count++; } return char_count; } // end copy_line