I am trying to write a function which reads bytes backwards from a file. I know exactly how it should work but since I just started programming in C++ I have no idea how to do that.
Lets say that I have a 2 GB large file and I want to allocate last 800 MBs into the system memory (backwards). I would like it to be efficient; not loading the whole file since I won’t be needing 1.2 GBs of it.
So far with my limited knowledge I was able to write this but I am stuck right now. Certainly there must much more elegant way how to do that.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main () {
// open the file
ifstream file;
file.open(filename, ios_base::binary);
//check for successful opening
if(!file.is_open()){
cout << "Error." << endl;
exit(EXIT_FAILURE);
}
//get the lenght of a file
file.seekg (0, file.end);
long length = file.tellg();
file.seekg (0, file.beg);
//read given amount of bytes from back and allocate them to memory
for (long i=0; i<=bytes_to_read-1; i++) {
file.seekg(-i, ios::end);
file.get(c);
//allocation process
}
return 0;
}