I'm reading the code below in Chapter 10 in the book called Computer System: A Programmer's Perspective. I understand all the code below except the line: bufp += nread; I found this line is pointless, because I don't see the point to increment the bufp pointer by nread?
Anyone can explain to me why bufp+= nread; exits there? Thank you very much!
ssize_t rio_readn(int fd, void *usrbuf, size_t n)
{
size_t nleft = n;
ssize_t nread;
char *bufp = usrbuf;
while(nleft > 0) {
if((nread = read(fd, bufp, nleft)) < 0) {
if (errno == EINTR)
nread = 0;
else
return -1;
}
else if (nread == 0)
break;
nleft -= nread;
bufp += nread;
}
return (n - nleft);
}
I have tried the code without bufp += nread;, it worked without it. And I've searched online everywhere if anyone had the same concern as mine, but I didn't find it.
If
bufpwas not incremented, then the nextread()would write over the previously read data. The way it works is thatread()deliversnreadbytes, which may be less thannleft. On the first call the read data occupies the buffer locationsusrbuf[0..nread-1]. On the next call ofread()afterbufp += nread;,bufpwill point tousrbuf[nread], which is the next available byte in the buffer after what was previously read.The only reason that code would work without the increment would be if the loop only ran once, or ran twice with the second
read()reading zero bytes. Those two would in fact be the normal case for reading regular files, since thenread()will get all of the available data. The reason that this function needs a loop, is that when reading from a pipe,read()will not wait fornleftbytes from the source, and instead return what is available at the time. (read()will wait for at least one byte or for EOF, so that if it returns zero, you know it got to EOF.) The loop assures thatnbytes are read if they eventually become available from the pipe.