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

rampion picture rampion · Mar 23, 2011 · Viewed 9.1k times · Source

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?

Answer

Steve Jessop picture Steve Jessop · Mar 23, 2011

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.