fstream - How to seekg() to position x from end

user2962533 picture user2962533 · Jul 21, 2015 · Viewed 8.2k times · Source

I'm looking for a way to set my get pointer at position x from the end of an fstream.

I tried

file.seekg(-x, ios_base::end);

But according to this question, this line is undefined behavior.

  • How can I, in any way, seek to position x from the end of a fstream?

Answer

Blood picture Blood · Jul 21, 2015

If you want to set your pointer at position x from the end, you need to know where the end is, so you need to begin with:

file.seekg(0, ios_base::end);
int length = file.tellg();

When you will know the file length, you can set your pointer:

file.seekg(length - x, ios_base::beg);