Find how many bytes are ready to be read from a FILE * file or file descriptor

Given FILE* or a file descriptor, is there a standard way to know how many bytes are ready to be read?

I cannot use s=ftell(f),fseek(f,0,SEEK_END),e=ftell(f),fseek(f,s,SEEK_SET),es , since FILE* just wraps the file descriptor I received from pipe(2) and I get ESPIPE when I try this.

I thought to use select(2) with a zero timeout to say that I have at least one byte ready to read, and then read the byte at a time, until select(2) told me to stop. This seems to be rather awkward and slow.

Is there a better way to do this?

+8
c pipe file-descriptor
source share
4 answers

read can return fewer bytes than you requested, and should do so if data is available, but it needs to be locked to fill the buffer.

So, the usual thing is to use select to detect readable ones, and then read any size of your preferred buffer. Alternatively, set O_NONBLOCK with fcntl and check the value -1 and errno EAGAIN.

+6
source share

It is not blessed with any modern standards, but the usual traditional unix way to do this is with ioctl(fd, FIONREAD, &n); See the answers to this question:

Determine the size of the channel without calling read ()

+4
source share

If you are only looking for something more efficient that reads 1 byte rather than the size of the data available in FIFO, you can:

  • Set the file descriptor to non-blocking mode.
  • Use select to know when data is available.
  • Call read with a large buffer. It can return less than what you requested (check the return code), or it can return -1 with EAGAIN or EWOULDBLOCK to indicate that you should return to the select call (no data)
+3
source share

Yes. fstat(2) . I looked at it earlier and saw that this would not work on FILE* (which is why I returned to the fseek anti-pattern), but did not think to return to the file descriptor.

0
source share

All Articles