// copyfile2.cpp - Gets the name of a file from the user, 
//                 say it is "moo.dat". It copies it line
//                 by line to file "moo.datout".

#include <iostream>  // It allows us to use cin, cout
#include <fstream>   // It allows us to use ifstream, ofstream ..
#include <string>      // It allows us to use strings

using namespace std;

enum copycode {copyok, cantfrom, cantto};
// Copy line by line the content of file fromfile
// to file tofile. Return copyok if success, cantfrom if cannot
// open fromfile, cantto if cannot open tofile.
copycode copyfilel(const char *fromfile, const char *tofile)
{
    // Open input file
	ifstream fin(fromfile);
	if (!fin)
		return (cantfrom);

	// Open output file
    ofstream fout(tofile);
    if (!fout)
		return (cantto);

    while (!fin.eof()) {
	   const int MAXLINE = 512;
	   char currentline[MAXLINE];  // line just read 
	   //getline reads all the way to the next \n included
	   //and stores all but \n in currentline adding a \0 at
	   //end, thus it stores the line as a C-string.
       fin.getline(currentline, MAXLINE-1);
       fout << currentline << endl;
       cout << currentline << endl;
    }

    cout << endl;
    fin.close();
    fout.close();
	return copyok;
}


void main (void)
{
    // Read the name of the input file from standard input
    string inFName;  // Name of the input file
    cout << "Enter a File Name: ";
    cin >> inFName;

    // Compute the name of the output file
    string outFName = inFName + "out"; // Name of the output file


    //c_str() is a method that applied to a string returns
	//the corresponding C-string.
	int rc = copyfilel(inFName.c_str(), outFName.c_str());
	
	if (rc == cantfrom)
		cout << "Cannot open " << inFName << endl;
	else if (rc == cantto)
		cout << "Cannot open " << outFName << endl;
	else // (rc == copyok)
		cout << "inFName is " << inFName << " outFName is " 
		     << outFName << endl;
}


