// copyWhileBreak.cpp
//
// Copies one text file to a new file.
// The input text file is entered as a command-line argument.
// The name of copy will be the name of the original file,
// prefixed by "copy-".
//
// Illustrates  how to read a file line by line,
// using a while loop with a break statement.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char** argv)
{
   if ( argc < 2 )  {
      cout << "This program copies a file." << endl;
      cout << "Enter the original filename as a command-line argument,"
                     << endl;
      cout << "The copy's filename will be prefixed by \"copy-\"."
                     << endl;
      return 0;
   }  // if

   // Prepare to read from file with filename
   // from command-line argument:
   ifstream inputFile;             // file input stream
   inputFile.open(argv[1]);

   // Check whether input file was opened successfully:
   if ( !inputFile )  {
      cout << "Cannot read file " << argv[1] << "." << endl;
      return 1;
   }  // if

   // Generate output filename:
   string filename = argv[1];      // input filename
   filename.insert(0, "copy-");    // output filename

   // Prepare to write to output file:
   ofstream outputFile;            // file output stream
   outputFile.open(filename.c_str());

   // Check whether output file was opened successfully:
   if ( !outputFile )  {
      cout << "Cannot write to file " << filename << "." << endl;
      return 1;
   }  // if

   // Begin reading the input file, one line at a time:
   string line;                     // the line most recently read

   while ( true )  {
      getline( inputFile, line );   // read a line from the file

      if ( ! inputFile )            // if end of file
         break;

      // Output the line most recently read:
      outputFile << line << endl;
   }  // while 

   return 0;
}  // function main