-5

it is file 
it is class
class size
loving file

becomes

loving file
class size
it is class
it is file 

simple by primitive data type never use vector , string etc . simple file handling in cpp

  • [related](http://stackoverflow.com/questions/10813930/read-a-file-backwards) – Paul Rooney May 02 '17 at 07:05
  • @Narendra kumawat: You should show your efforts trying to solve the problem. As this is your first time I guess, I will help you, but for future please stick to the site rules. [Take this tour](http://stackoverflow.com/tour) and [learn to ask here](http://stackoverflow.com/help/mcve). For hep [goto this page](http://stackoverflow.com/help). – Shadi May 02 '17 at 09:41

1 Answers1

0

As you would not like to use arrays, vectors or anything like that here you are a solution that may help you.

Note: using a temp storage will make it more compact.

The idea is to use three function:

1- get_line_num: counts line numbers of the file.
2- goto_line: puts the reading cursor into a specific line.
3- reset: put the reading cursor in the beginning of the file.

Program has a lot of I/O which is not good, but as you do not want to use advanced structures, this may help.

algorithm:

  1. open original file.
  2. open temp file.
  3. loop from last line to first line
  4. read line from input file.
  5. add the line into the temp output file
  6. end loop.
  7. delete the old original file.
  8. rename the temp file same as the original file.

Headers:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int get_line_num(ifstream& myfile);
ifstream& goto_line(ifstream& myfile, int line_num);
void reset(ifstream& myfile);

int main()
{
    ifstream in;
    ofstream out;

    string line;

    char* original = "original file name";
    char* dest = "temp file name";

    in.open(original);
    out.open(dest, ios::app);

    int num_of_lines = get_line_num(in);

    for (int i = num_of_lines ; i ; --i)

    {
         goto_line(in, i);
         getline(in, line);
         reset (in);
         out << line << "\n";
    }

    in.close();
    out.close();

    remove(original);
    rename(dest, original);

    cout <<"\n\n\n";
}


int get_line_num(ifstream& myfile)
{
    int number_of_lines = 0;
    string line;

    while (getline(myfile, line))
        ++number_of_lines;

    reset (myfile);

    return number_of_lines;
}

ifstream& goto_line(ifstream& myfile, int line_num)
{
    string s;
    myfile.seekg(ios::beg);
    for(int i = 1; i < line_num; ++i)
        getline(myfile, s);

    return myfile;
}

void reset(ifstream& myfile)
{
    myfile.clear();
    myfile.seekg(0, ios::beg);
}
Shadi
  • 1,701
  • 2
  • 14
  • 27