Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

916 Solutions to Selected Exercises Appendix C


return(flags);
}
static off_t
find_end(char *buf, size_t len)
{
off_t off = 0;
while (off < len) {
if (buf[off] == 0)
break;
off++;
}
return(off);
}
static int
mstream_read(void *cookie, char *buf, int len)
{
int nr;
struct memstream *ms = cookie;
if (!(ms->flags & MS_READ)) {
errno = EBADF;
return(-1);
}
if (ms->curpos >= ms->vsize)
return(0);
/* can only read from curpos to vsize */
nr = MIN(len, ms->vsize - ms->curpos);
memcpy(buf, ms->buf + ms->curpos, nr);
ms->curpos += nr;
return(nr);
}
static int
mstream_write(void *cookie, const char *buf, int len)
{
int nw, off;
struct memstream *ms = cookie;
if (!(ms->flags & (MS_APPEND|MS_WRITE))) {
errno = EBADF;
return(-1);
}
if (ms->flags & MS_APPEND)
off = ms->vsize;
else
off = ms->curpos;
nw = MIN(len, ms->rsize - off);
memcpy(ms->buf + off, buf, nw);
ms->curpos = off + nw;
Free download pdf