Reverse a text file from input to output

Okay, so I have this code, and i need to modify if so that input file will be reversed in the output file... I thought about adding a string, but i don't know how. It's the first time i'm working with input/output file, or better, the first time i'm working with fstream!
To be clear, if in my input file is "hello world", the output should be "dlrow olleh". Sorry for my english, and thank you.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
 #include <cstdlib>
#include <iostream>
#include <fstream>


using namespace std;

int main()
{
    
    std::ifstream infile ("input.txt",std::ifstream::binary);
    std::ofstream outfile ("output.txt",std::ofstream::binary);

  // get size of file
    infile.seekg (0,infile.end);
    long size = infile.tellg();
    infile.seekg (0);
    
    
     if (size > 1024*1024) 
           cout << "File too big\n";
       
    else {
  
  
  // allocate memory for file content
    char* buffer = new char[size];
  

  
  // read content of infile
    infile.read (buffer,size);

  


  // write to outfile
    outfile.write (buffer,size);

  // release dynamically-allocated memory
   delete[] buffer;

}
	cout << "End of file - Output created" << endl;
	outfile.close();
	infile.close();
	
    system("PAUSE");
    return EXIT_SUCCESS;
}
Last edited on
The easiest way is to convert your buffer to a std::string and use a reverse iterator to output your reversed string to your output file:

http://www.cplusplus.com/reference/string/string/rbegin/
Topic archived. No new replies allowed.