Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a file descriptor is seekable?

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?

like image 735
R.. GitHub STOP HELPING ICE Avatar asked Jul 13 '10 15:07

R.. GitHub STOP HELPING ICE


People also ask

How do I know if a file descriptor is valid?

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.

What is a seekable file?

A file is seekable if it allows access to the file stream, like the seek() method.

What is the return value of Lseek?

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.

How do I get the file descriptor of a directory?

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.


1 Answers

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.

like image 140
casablanca Avatar answered Oct 22 '22 13:10

casablanca