[Solved] Reverse content of a file without using an array in C++ [closed]


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);
}

solved Reverse content of a file without using an array in C++ [closed]