如何确定文件描述符是否可搜索? [英] How to determine if a file descriptor is seekable?

查看:86
本文介绍了如何确定文件描述符是否可搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(在POSIX系统上)是否有任何可移植的方式来确定文件描述符是否可搜索?我的想法是使用lseek(fd, 0, SEEK_CUR);并检查返回值是否为-1,但是我不确定这是否会产生假阴性或假阳性.使用fstat并假设可搜索/不可搜索的文件类型听起来不是一个好主意.还有其他想法吗?

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?

推荐答案

lseek方法似乎很合理.当然,它不会导致误报-如果确实如此,则实现中会出现严重错误.另外,根据 POSIX规范,如果描述符是管道,FIFO或套接字,因此从理论上讲,您也不应该具有误报.唯一剩下的问题是不同系统符合规范的程度.但是,似乎任何其他方法,无论它们可能是什么,都肯定比此方法具有较小的可移植性.

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.

这篇关于如何确定文件描述符是否可搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆