How to determine if a file descriptor is seekable?

跟風遠走 提交于 2019-12-05 02:22:53

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.

You can use fstat(), then the S_ISREG macro on the mode field of the stat struct to check whether it's a regular file; a regular file, per definiton, is seekable whereas a "non-regular" (special) file might not be (I don't know if there are special files that are also seekable).

But yeah, checking the return value of lseek() and errno == ESPIPE should also work. In principle, the effect of lseek() on devices which are incapable of seeking is implementation-defined, so beware of nasal daemons.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!