readline.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* include readline */
  2. #include "unp.h"
  3. static int read_cnt;
  4. static char *read_ptr;
  5. static char read_buf[MAXLINE];
  6. static ssize_t
  7. my_read(int fd, char *ptr)
  8. {
  9. if (read_cnt <= 0) {
  10. again:
  11. if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) {
  12. if (errno == EINTR)
  13. goto again;
  14. return(-1);
  15. } else if (read_cnt == 0)
  16. return(0);
  17. read_ptr = read_buf;
  18. }
  19. read_cnt--;
  20. *ptr = *read_ptr++;
  21. return(1);
  22. }
  23. ssize_t
  24. readline(int fd, void *vptr, size_t maxlen)
  25. {
  26. ssize_t n, rc;
  27. char c, *ptr;
  28. ptr = vptr;
  29. for (n = 1; n < maxlen; n++) {
  30. if ( (rc = my_read(fd, &c)) == 1) {
  31. *ptr++ = c;
  32. if (c == '\n')
  33. break; /* newline is stored, like fgets() */
  34. } else if (rc == 0) {
  35. *ptr = 0;
  36. return(n - 1); /* EOF, n - 1 bytes were read */
  37. } else
  38. return(-1); /* error, errno set by read() */
  39. }
  40. *ptr = 0; /* null terminate like fgets() */
  41. return(n);
  42. }
  43. ssize_t
  44. readlinebuf(void **vptrptr)
  45. {
  46. if (read_cnt)
  47. *vptrptr = read_ptr;
  48. return(read_cnt);
  49. }
  50. /* end readline */
  51. ssize_t
  52. Readline(int fd, void *ptr, size_t maxlen)
  53. {
  54. ssize_t n;
  55. if ( (n = readline(fd, ptr, maxlen)) < 0)
  56. err_sys("readline error");
  57. return(n);
  58. }