WAP to print the content of a file in reverse order
Objective
Write a C++ program to print the contents of a file in reverse order.
Algorithm / Approach
- Open a file using
ifstream. - Move the internal file pointer to the very end of the file:
in.seekg(0, ios::end). - Get the total size of the file in bytes:
size = in.tellg(). - Loop
jfrom 1 tosize. - Move the pointer backward one step at a time from the end:
in.seekg(-j, ios::end). - Read and print the character at that specific location.
main.cpp
#include<iostream>
#include<fstream>
using namespace std;
class Test {
public:
void rev() {
char c;
char name[10];
ifstream in;
cout<<"Enter File Name: ";
cin.getline(name,10);
in.open(name,ios::in);
if(!in){
cout<<"File doesn't exists";
}
else {
in.seekg(0,ios::end);
int size=in.tellg();
for (int j=1; j<=size; j++){
in.seekg(-j, ios::end);
c=in.get();
cout<< c;
}
}
in.close();
}
};
int main() {
Test t;
t.rev();
return 0;
}
Expected Output
Enter File Name: apps.txt srennigeB rof depoleveD
Explanation of the Program
- Every open file has an invisible "pointer" that tracks where the next read/write operation will happen.
- The
seekg()(Seek Get) function allows us to manually move this pointer anywhere in the file.tellg()(Tell Get) tells us exactly where the pointer currently is. By moving the pointer backwards from the end (ios::end) and reading one character at a time, we can read the file in reverse.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)