cstdiofseek

Detect when `fseek()` goes beyond end of file


In <stdio.h>, the function fseek() seems allowed to skip way beyond the end of its file handler, without producing any error code.

While I can understand the behavior when the FILE* handler is set to "w" write, since it seems to allow writing sparse files, I don't understand the point of such a feature when it's "r" read-only.

Anyway, as a consequence, it's not possible to detect that end of file was overshot with fseek(), and next attempt to fread() simply returns 0, as if end of file was just reached normally.

What could be a work around to detect that fseek() overshot past the end of file ?


Solution

  • ... I don't understand the point of such a feature when it's "r" read-only.

    I don't think that this is an intended feature but I think that it was simply easier to implement this behavior in the operating system (not in the C libraries).

    And if you don't call fread() immediately after fseek(), another program may append data to the file between the two function calls, so the new file pointer is no longer after the end of the file when you call fseek().

    (I just checked that this really works under Linux and I think it would work under Windows and MacOS, too.)

    What could be a work around to detect that fseek() overshot past the end of file?

    You could check the file size by setting the file pointer to the end using fseek(..., 0, SEEK_END); and reading the file pointer back using ftell().

    Then you know the size of the file and may compare the new file pointer (that you pass to fseek()) to the size of the file "manually" (in an if()...else check).