Search code examples
c++cfilefseek

Problem with fseek


Here is my code.

if(fseek(file,position,SEEK_SET)!=0)
{
  throw std::runtime_error("can't seek to specified position");
}

I used to assume that even if position is greater than num of characters in file this code would work correct (i.e. throw error), but it wouldn't. So I want to know how can I handle seeking failure when trying to seek out of file range?


Solution

  • Well, you can always check for file length before doing the fseek.

    void safe_seek(FILE* f, off_t offset) {
        fseek(f, 0, SEEK_END);
        off_t file_length = ftell(f);
        if (file_length < offset) {
            // throw!
        }
        fseek(f, offset, SEEK_SET);
    }
    

    Be aware though that this is not thread safe.