For files that contain both text lines and binary data (such as the HTTP responses), we provide a buffered version of
rio_readn
, called
rio_readnb
, that transfers raw bytes from an internal read buffer. The rio_readnb function reads up to n bytes from file rp to memory location usrbuf. The format of a read buffer is showed below.
#define RIO_BUFSIZE 8192
typedef struct {
int rio_fd; // Descriptor for this internal buf
int rio_cnt; // Unread bytes in internal buf
char *rio_bufptr; // Next unread byte in internal buf
char rio_buf[RIO_BUFSIZE]; // Internal buffer
} rio_t;
The heart of the robust read routine is the rio_read function showed below. The rio_read function is a buffered version of the Unix read function.
static ssize_t rio_read(rio_t *rp, char *usrbuf, size_t n)
{
while (rp->rio_cnt <= 0) { // Refill if buf is empty
rp->rio_cnt = read(rp->rio_fd, rp->rio_buf,
sizeof(rp->rio_buf));
if (rp->rio_cnt < 0) {
if (errno != EINTR) // Interrupted by signal
return -1; // handle return
}
else if (rp->rio_cnt == 0) // EOF
return 0;
else
rp->rio_bufptr = rp->rio_buf; // Reset buffer ptr
}
// Copy min(n, rp->rio_cnt) bytes from internal buf to user buf
int cnt = n;
if (rp->rio_cnt < n)
cnt = rp->rio_cnt;
memcpy(usrbuf, rp->rio_bufptr, cnt);
rp->rio_bufptr += cnt;
rp->rio_cnt -= cnt;
return cnt;
}
When rio_read is called with a request to read n bytes, there are rp->rio_cnt unread bytes in the read buffer. If the buffer is empty, then it is replenished with a call to read. Receiving a short count from this invocation of read is not an error, and simply has the effect of partially filling the read buffer.
To an application program, the rio_read function has the same semantics as the Unix read function. The similarity of the two functions makes it easy to build different kinds of buffered read functions by substituting rio_read for read. For example, the rio_readnb function, which performs robust buffered reading, has the same structure as rio_readn, with rio_read substituted for read.
ssize_t rio_readnb(rio_t *rp, void *usrbuf, size_t n)
{
size_t nleft = n;
ssize_t nread;
char *bufp = usrbuf;
while (nleft > 0) {
if ((nread = rio_read(rp, bufp, nleft)) < 0) {
if (errno == EINTR) // Interrupted by signal handle return
nread = 0; // Call read() again
else
return -1; // errno set by read()
}
else if (nread == 0)
break; // EOF
nleft -= nread;
bufp += nread;
}
return (n - nleft); // Return >= 0
}