In: Computer Science
ok here is my homework
This assignment focuses on file streams.
Your program will accept the name of an input file from the user, and the name of an output file from the user. You may assume the input file contains no more than 100 lines.
Your program will write the lines of the input file to the output file in reverse line order, i.e. the first line of the input file becomes the last line of the output file, the second line of the input file becomes the second-to-the-last line of the output file, and so forth. Note that the lines themselves are not reversed, only the order in which the lines appear.
NOTE : FEEL FREE TO ASK ANY DOUBTS IN THE COMMENT SECTION
input.txt
CODE
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(){
// variables to store file names
char in[20],out[20];
// filestream variables
fstream infile,outfile;
cout << "\n Enter Input Filename: ";
cin >> in; // reading input file
name
cout << "\n Enter Output Filename: ";
cin >> out;// reading output file name
// opening infile in read mode
// opening outfile in write mode
infile.open(in,ios::in);
outfile.open(out,ios::out);
// if unable to open file showing error
// and also exit from program
if(!infile.is_open() || !outfile.is_open()){
cout << "Error while Opening
or Creating file";
return 0;
}
int count=0; // variable to store current
file lines count
string line="";// to store line
// Loop until file does not reach end of file
while(getline(infile,line))
{
// increase line count
count = count + 1;
}
// closing file and opens again in read mode
infile.close();
infile.open(in,ios::in);
// string array to store lines
string lines[count];
// starting index of array from end
int index=count-1;
// Loop until doesnot reaches end of file
while(getline(infile,line)){
// adding line to lines array at
index
lines[index]=line+"\n";
index=index-1; // decrementing
index
}
// writing lines in reverse order to outfile
for(int i=0;i<count;i++){
outfile << lines[i];//
writing to file
}
// Closing infile adn outfile
infile.close();
outfile.close();
cout << "\n Data Successfully Inserted";
return 0;
}
OUTPUT in CONSOLE
output.txt
CODE in EDITOR
DEAR SIR, PLEASE CONSIDER MY EFFORT AND PLEASE DON'T FORGET TO GIVE AN UP VOTE
Thank YOU :-)