Search code examples
c++fstreamseekg

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


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?

Solution

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