How to find out if offset cursor is at EOF with lseek()?

JohnnyFromBF picture JohnnyFromBF · Jan 18, 2015 · Viewed 7.1k times · Source

How can I find out if the offset cursor is currently at EOF by using lseek() only?

Answer

mafso picture mafso · Jan 18, 2015

lseek returns the (new) position. If it's acceptable that the file position is at the end after the test, the following works:

off_t old_position = lseek(fd, 0, SEEK_CUR);
off_t end_position = lseek(fd, 0, SEEK_END);
if(old_position == end_position) {
    /* cursor already has been at the end */
}

Now, the cursor is at the end, whether it already has been there or not; to set it back, you can do lseek(fd, old_position, SEEK_SET) afterwards.

(I omitted checks for errors (return value of (off_t)-1) for sake of shortness, remember to include them in the real code.)

An alternative, though using another function, would be to query the current position as above and fstat the file to see if the st_size field equals the current position.

As a note, the end-of-file condition is set for streams (FILE *, not the int file descriptors) after an attempt to read past the end of the file, the cursor being at the end is not enough (that is, this approach is not the file descriptor equivalent to feof(stream)).