In: Computer Science
Write a C++ programm which
Please add comments next to the code, so I can learn from the solution. Also please use beginner coding, nothing too advance.
Below is the solution:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fRead,fWrite; //create a file stream to read
and write a file
char fname1[20], fname2[20]; //variable of input and
output file name
string line; //variable to read file line
cout<<"Enter source file name with extension
(input.txt) : "; //ask to enter file name to read
gets(fname1); //file name from keyboard
fRead.open(fname1); //open file to read
if(!fRead) //if file is not found to read
{
cout<<"Error!! in opening
file!"; //print the error
exit(1); //exit
}
cout<<"Enter output file name with extension
(output.txt) : "; //ask to enter file name to write
gets(fname2); //file name from keyboard
fWrite.open(fname2); //open a file to write
if(!fWrite) //if file not found
{
cout<<"Error!! in opening
file!";
fRead.close(); //close file
opened
exit(2); //exit
}
while (getline(fRead, line) ) //loop until end of the
file line by line
{
fWrite<<line<<endl;
//write each line to the file
}
cout<<"File copied successfully..!!"; //message
to file content written
fRead.close(); //close the file
fWrite.close(); //close the file
return 0;
}
sample output:
Enter source file name with extension (input.txt) :
input.txt
Enter output file name with extension (output.txt) :
output.txt
File copied successfully..!!
Enter source file name with extension (input.txt) :
input1.txt
Error!! in opening file!
input.txt:
This is a first line.
This is another line.
1 2 3 4 5
output.txt:
This is a first line.
This is another line.
1 2 3 4 5