If your main intention is to spend time, you want to find the correct position, read the file in the opposite direction, and then cancel the data in memory. If you are reading a large amount and want only a small amount of memory at a time, you can change this a bit to read (for example) 16 or 64 Kilobyte snippets.
Once you have a piece of data in memory, you have two options. You can handle it from end to back to start, or you can undo it and then process it from start to end. The latter may look something like this:
// Warning: I have only tested this, not proven it correct. std::vector<char> read_backwards(std::istream &is, int size) { std::vector<char> buffer; buffer.resize(size); is.seekg(-size, std::ios::end); is.read(&buffer[0], size); std::reverse(buffer.begin(), buffer.end()); return buffer; }
Attempting to actually read the file backwards can (and often will) lead to a serious performance issue. To be specific, the standard library often flushes its buffers every time it searches the stream, so every read immediately after the search usually results in a kernel function call to read data from disk (or at least from the OS cache).
If you care about why this is so: the C ++ standard bases its description of how files work on the C standard. The C standard says that if you open a stream for reading and writing, you need to look for a search in the stream when / if you switch from read to write (or vice versa). Because of this, quite a few search implementations in the stream clear the buffer for each search, just in case you can switch from write to read and you need to read the data that was in the write buffer before the search.
Usually this does not really matter: the search will often go beyond the range that is in the buffer, so you still have to read data from disk. However, in the specific case discussed here, buffering can work quite well while you read the data βforwardβ and then cancel it, rather than performing a search for each byte. Although it is best to use the largest buffer that is practical, even a fairly small buffer can make a big difference in speed.