util.c

Go to the documentation of this file.
00001 #include <unistd.h>
00002 #include <string.h>
00003 
00004 #include "echo.h"
00005 
00006 static ssize_t my_read(int fd, char *ptr)
00007 {
00008   static int read_cnt = 0;
00009   static char *read_ptr;
00010   static char read_buf[MAXLINE];
00011 
00012   if (read_cnt <= 0) {
00013   again:
00014     if ((read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
00015       if (errno == EINTR)
00016     goto again;
00017       return (-1);
00018     } else if (read_cnt == 0)
00019       return (0);
00020     read_ptr = read_buf;
00021   }
00022 
00023   read_cnt--;
00024   *ptr = *read_ptr++;
00025   return (1);
00026 }
00027 
00028 ssize_t readline(int fd, void *vptr, size_t maxlen)
00029 {
00030   int n, rc;
00031   char c, *ptr;
00032 
00033   ptr = vptr;
00034   for (n = 1; n < maxlen; n++) {
00035     if ((rc = my_read(fd, &c)) == 1) {
00036       *ptr++ = c;
00037       if (c == '\n')
00038     break;          /* newline is stored, like fgets() */
00039     } else if (rc == 0) {
00040       if (n == 1)
00041     return (0);     /* EOF, no data read */
00042       else
00043     break;          /* EOF, some data was read */
00044     } else
00045       return (-1);      /* error, errno set by read() */
00046   }
00047 
00048   *ptr = 0;         /* null terminate like fgets() */
00049   return (n);
00050 }
00051 
00052 /* end readline */
00053 
00054 ssize_t Readline(int fd, void *ptr, size_t maxlen)
00055 {
00056   ssize_t n;
00057 
00058   if ((n = readline(fd, ptr, maxlen)) < 0)
00059     perror("readline error");
00060   return (n);
00061 }
00062 
00063 ssize_t             /* Write "n" bytes to a descriptor. */
00064 writen(int fd, const void *vptr, size_t n)
00065 {
00066   size_t nleft;
00067   ssize_t nwritten;
00068   const char *ptr;
00069 
00070   ptr = vptr;
00071   nleft = n;
00072   while (nleft > 0) {
00073     if ((nwritten = write(fd, ptr, nleft)) <= 0) {
00074       if (errno == EINTR)
00075     nwritten = 0;       /* and call write() again */
00076       else
00077     return (-1);        /* error */
00078     }
00079 
00080     nleft -= nwritten;
00081     ptr += nwritten;
00082   }
00083   return (n);
00084 }
00085 
00086 /* end writen */
00087 
00088 void Writen(int fd, void *ptr, size_t nbytes)
00089 {
00090   if (writen(fd, ptr, nbytes) != nbytes)
00091     perror("writen error");
00092 }