File program to read in reverse order the contents of a file.

it's urgent, i've my exam tomorrow. please correct the errors. i've done so far.


#include<iostream>
#include<fstream>
#include<cstdlib>
#include<iomanip>
using namespace std;

int main()
{
ifstream fin; char ch; int size=0;
fin.open("txtfile.txt");
if(!fin)
{
cout<<"\nFile Opening Error...";
exit(1);
}
cout<<"\nContents of file in original order:\n";
while((ch = fin.get())!= EOF)
{
cout.put(ch);
size++;
}
cout<<"\nContents of file in reverse order:\n";
cout<<endl<<size<<endl;

fin.seekg(size,ios::end);

while(fin)
{
ch=fin.get();
cout.put(ch);
size--;
fin.seekg(size);
}
fin.close();

cin.setf(ios::unitbuf);
cin.get();
return 0;
}
Last edited on
Since you don't name any errors, for me personally, there are no errors to correct.
hello, bugbyte
it doesnot print the reverse order.
Make one pass forward through the file, pushing each character read to a stack.
For the reverse order, pop characters one by one from the stack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<fstream>
//#include<cstdlib>
//#include<iomanip>
#include <stack> // *** added
// using namespace std;

int main()
{
    std::ifstream fin( __FILE__ /* "txtfile.txt" */ );
    if( !fin.is_open() )
    {
        std::cerr << "\nFile Opening Error...\n";
        return 1 ;
    }
    std::stack<char> stk ;

    std::cout << "\nContents of file in original order:\n";
    char ch;
    while( fin.get(ch) ) // canonical
    {
        std::cout << ch ;
        stk.push(ch) ;
    }
    // note: the stream is in a failed/eof state here.
    // we don't need it any more, but if we did, 
    // we would have to first clear the state before using it
    // see: http://en.cppreference.com/w/cpp/io/basic_ios/clear
    

    std::cout << "\n\n=================\n\nContents of file in reverse order:\n";
    while( !stk.empty() )
    {
        std::cout << stk.top() ;
        stk.pop() ;
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/be1ead492a9434b6
Thank you JLBorges.
edit: nvm, what I posted was wrong.
Last edited on
Topic archived. No new replies allowed.