Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 862
rampion Avatar asked Mar 23 '11 17:03

rampion


Video Answer


1 Answers

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.

like image 135
Steve Jessop Avatar answered Sep 20 '22 13:09

Steve Jessop