// copy.cpp
//
// Copies one text file to a new file.
// The input text file name is entered by the user.
// The name of copy will be the name of the original file,
// prefixed by "copy-".
//
// Illustrates how to read a file one byte at a time,
// and illustrates use of string insert function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Announce purpose of program:
cout << "This program copies a text file, fixing "
<< "end-of-line markers." << endl;
cout << "The copy's filename will be prefixed by \"copy-\"."
<< endl;
// Obtain filename from user input, as a string class object:
cout << "Enter filename:> ";
string filename;
getline(cin, filename);
// Prepare to read from file:
ifstream inputFile; // file input stream
inputFile.open(filename.c_str());
// Check whether input file was opened successfully:
if ( !inputFile )
{
cout << "Cannot read file " << filename << "." << endl;
return 1;
} // if
// Generate output 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 byte at a time:
char currentByte; // the byte most recently read
inputFile.get(currentByte); // read the FIRST byte, if any
while ( inputFile ) // i.e. while not end-of-file
{
// Output the byte most recently read:
outputFile << currentByte;
// Read NEXT byte from input file, if any bytes are left:
inputFile.get(currentByte);
} // while not end of file
// Announce completion of output file:
cout << "File " << filename << " has been created." << endl;
return 0;
} // function main