Is there any portable way (on POSIX systems) to determine if a file descriptor is seekable? My thought is to use lseek(fd, 0, SEEK_CUR);
and check if the return value is -1, but I'm uncertain if this could give false negatives or false positives. Using fstat
and making assumptions about what types of files are seekable/nonseekable does not sound like a good idea. Any other ideas?
fcntl(fd, F_GETFD) is the canonical cheapest way to check that fd is a valid open file descriptor. If you need to batch-check a lot, using poll with a zero timeout and the events member set to 0 and checking for POLLNVAL in revents after it returns is more efficient.
A file is seekable if it allows access to the file stream, like the seek() method.
RETURN VALUEUpon successful completion, lseek() returns the resulting offset location as measured in bytes from the beginning of the file. Otherwise, a value of (off_t)-1 is returned and errno is set to indicate the error.
You can't get a file descriptor for a directory. Actually, you can get an FD to a directory, but you get your error if you try to use O_RDWR . Use O_RDONLY . If you use dir = opendir(...); to open a directory, you can use dirfd(dir) to obtain the underlying descriptor.
The lseek
method seems reasonable. It certainly can't cause a false negative - if it did, something is seriously wrong with the implementation. Also, according to the POSIX spec, it is supposed to fail if the descriptor is a pipe, FIFO or socket, so theoretically you shouldn't have false positives either. The only remaining question is how well different systems comply with the specs. However, it seems like any other methods, whatever they may be, would definitely be less portable than this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With