查找有多少字节可供从 FILE* 或文件描述符中读取
给定一个 FILE* 或文件描述符,是否有标准方法来判断有多少字节可供读取?
自 以来,我无法使用
只是包装我从 s=ftell(f),fseek(f,0,SEEK_END),e=ftell(f),fseek(f,s,SEEK_SET),es
FILE*pipe(2)< 获得的文件描述符/code>
,当我尝试时,我得到了
ESPIPE
。
我正在考虑使用 select(2)
和零超时来告诉我至少有一个字节可供读取,然后一次读取一个字节,直到 select(2 )
让我停下来。但这看起来有点笨重和缓慢。
有更好的方法吗?
Given a FILE*
or a file descriptor, is there a standard way to tell how many bytes are ready to be read?
I can't use s=ftell(f),fseek(f,0,SEEK_END),e=ftell(f),fseek(f,s,SEEK_SET),e-s
since the FILE*
is just wrapping a file descriptor I got from pipe(2)
, and I get ESPIPE
when I try that.
I was thinking of using select(2)
with a zero timeout to tell that I have at least one byte ready to be read, and then reading a byte at a time until the select(2)
told me to stop. This seems kinda clunky and slow though .
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
read
可以返回比您要求的更少的字节,并且如果数据可用则必须这样做,但它需要阻塞才能填充缓冲区。因此,通常的做法是使用
select
来检测可读性,然后读取您喜欢的缓冲区大小。或者,使用 fcntl 设置 O_NONBLOCK,并检查 -1 返回值和 errno EAGAIN。read
can return fewer bytes than you asked for, and must do so if data is available, but it would need to block in order to fill the buffer.So the usual thing is to use
select
to detect readable, then read whatever your favoured buffer size is. Alternatively, set O_NONBLOCK using fcntl, and check for -1 return value and errno EAGAIN.如果您只是在寻找比 1 字节读取更高效的东西,而不是 FIFO 上可用数据的大小,那么您可以:
select
了解数据何时可用read
。它返回的内容可能少于您请求的内容(检查返回代码),或者可能返回 -1 并带有EAGAIN
或EWOULDBLOCK
来指示您应该去返回调用select
(没有可用数据)If you're only looking for something more efficient that 1 byte reads, and not the size of the available data on the FIFO, then you can:
select
to know when data is availableread
with a large buffer. It might return less than you requested (check the return code), or it might return -1 withEAGAIN
orEWOULDBLOCK
to indicate you should go back to callingselect
(no data is availabe)它没有受到任何现代标准的祝福,但执行此操作的常见传统 unix 方法是使用 ioctl(fd, FIONREAD, &n); 请参阅此问题的答案:
在不调用 read() 的情况下确定管道的大小
It's not blessed by any modern standards, but a common traditional unix way to do this is with
ioctl(fd, FIONREAD, &n);
See the answers to this question:Determine the size of a pipe without calling read()
扩展 R 给出的答案..
一个大型的现实世界 软件框架 使用 ioctl 来找出像这样的字节(折扣错误检查):
FreeBSD、Linux 和 Solaris (来源):
IRIX (来源):
Windows (来源):
Extending on the answer given by R..
A large real-world software framework uses ioctl to find out the number of bytes like this (discounting error checks):
FreeBSD, Linux, and Solaris (source):
IRIX (source):
Windows (source):
多伊。
fstat(2)
。我之前浏览过它,发现它不适用于FILE*
(这就是为什么我回到了fseek
反模式),但没有考虑依靠文件描述符。doy.
fstat(2)
. I glanced at it earlier, and saw it wouldn't work onFILE*
, (which is why I fell back to thefseek
anti-pattern), but didn't think to fall back on the file descriptor.