Read a file backwards?
c++
Solution
As per comment, a possible (quite simple) alternative would be read the lines into a `vector`. For example:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::ifstream in("main.cpp");
if (in.is_open())
{
std::vector<std::string> lines_in_reverse;
std::string line;
while (std::getline(in, line))
{
// Store the lines in reverse order.
lines_in_reverse.insert(lines_in_reverse.begin(), line);
}
}
}
EDIT:
As per jrok's and Loki Astari's comments, `push_back()` would be more efficient but the lines would be in file order, so reverse iteration (`reverse_iterator`) or `std::reverse()` would be necessary:
std::vector<std::string> lines_in_order;
std::string line;
while (std::getline(in, line))
{
lines_in_order.push_back(line);
}
Problem
Is there a way to read a file backwards, line by line, without having to go through the file from the beginning to start reading backwards?