#include "unp.h"
ssize_t
readn(int fd, void *vptr, size_t n)
{
size_t nleft;
ssize_t nread;
char *ptr;
ptr = vptr; //to save vptr into nleft, that nleft can be changed, and vptr is stable
nleft = n; //to save n into nleft
while (nleft>0) {
if ( (nread = read(fd, ptr, nleft) ) < 0 { //save read() into nread
if (errno == EINTR) /* if <0, that means the procedure meets
interruption and set errno as EINTR */
nread = 0;
else
return(-1);
} else if (nread == 0) /* if =0, that means the file(fd) is read completely
or there is no byte to read from the beginning */
break;
nleft -= nread; //if nleft>0 , read the file(fd) and count nleft -= nread
ptr += nread; //for sure ptr move rightward for nread byte
}
return (n - nleft); /* at last the nleft should be 0, so we have already
read n-0=n bytes(while n is 0 or a positive integer),
or nleft is -1, we have read -1-(-1)=0 byte */
}
#include "unp.h"
ssize_t
writen(int fd, const void *vptr, size_t n)
{
size_t nleft;
ssize_t nwritten;
const char *ptr; //cuz we use writen(), we don't call it again, so it's const char
ptr = vptr;
nleft = n;
while (nleft > 0) {
if ( (nwritten = write (fd, ptr, nleft) ) <= 0 {
if (nwritten < 0 && errno == EINTR)
nwritten = 0; //and call write() again
else
return (-1);
}
nleft -= nwritten; //nleft = nwritten- nleft
ptr += nwritten; //ptr move rightward for nwritten bytes
}
return (n); //we have written n bytes
}
#include "unp.h"
ssize_t
readline(int fd, void *vptr, size_t maxlen)
{
ssize_t n, rc;
char c, *ptr;
ptr = vptr;
for (n = 1; n < maxlen; n++) {
again:
if ( (rc = read(fd, &c, 1) ) == 1) { //if we read 1 line as the parameter sets
*ptr++ = c; /* ptr move rightward for c bytes,
and c is the string we have read in this line */
if (c == '\n') // if this line is \n
break; // we break this if
} else if (rc == 0) { /* if we read 0 line form this operate
that means all done or the file has 0 line or just fail*/
*ptr = 0; // set *ptr to NULL
return (n-1); // not we have read n-1 line
} else {
if (errno == EINTR) //errno case, return -1
return (-1);
} goto again; //goto again until n = maxlen
}
*ptr = 0 //set *ptr to NULL, just like fgets()
return(n); //we have read n lines
}