Search code examples
ceoffseek

fseek on EOF character


I'm currently using fgetc() in loop for reading whole file.

But I need to detect EOF in two iterations of this loop. I know that EOF can't be returned to stream using ungetc().

What about using

fseek(file, -1, SEEK_CUR)

Is it safe and portable to get before EOF using fseek and read it again?

Thanks.


Solution

  • You can use

    fseek(file, 0, SEEK_END)
    

    If you try to read from it, you'll get your second EOF.

    EDIT:

    Reading the reference more carefully: "Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability)."

    I guess your solution is the best one in terms of portability.

    Just be careful with fseek (as a note because this is not your case I believe): Using fseek to backtrack