home *** CD-ROM | disk | FTP | other *** search
/ Atari FTP / ATARI_FTP_0693.zip / ATARI_FTP_0693 / Mint / mntlib25.zoo / textio.c < prev    next >
C/C++ Source or Header  |  1992-09-17  |  1KB  |  73 lines

  1. /*
  2.  * textio: read/write routines for text. These can be used in programs
  3.  * where read and write are used instead of the (preferred) stdio routines
  4.  * for manipulating text files, by doing something like
  5.  *  #define read _text_read
  6.  * Written by Eric R. Smith and placed in the public domain.
  7.  *
  8.  * Modified to fix a bug causing a premature EOF signal -
  9.  *   Michal Jaegermann, June 1991.
  10.  */
  11.  
  12. #include <stdio.h>
  13. #include <unistd.h>
  14.  
  15. int
  16. _text_read(fd, buf, nbytes)
  17.     int fd;
  18.     char *buf;
  19.     int nbytes;
  20. {
  21.     char *to, *from;
  22.     int  r;
  23.  
  24.     do {
  25.         r = read(fd, buf, nbytes);
  26.         if (r <= 0)        /* if EOF or read error - return */
  27.             return r;
  28.         to = from = buf;
  29.         do {
  30.             if (*from == '\r')
  31.                 from++;
  32.             else
  33.                 *to++ = *from++;
  34.         } while (--r);
  35.     } while (buf == to);    /* only '\r's? - try to read next nbytes */
  36.     return (int)(to - buf);
  37. }
  38.  
  39. int
  40. _text_write(fd, from, nbytes)
  41.     int fd;
  42.     char *from;
  43.     int nbytes;
  44. {
  45. #ifdef __SOZOBON__
  46.     char buf[1024+2];
  47. #else
  48.     char buf[BUFSIZ+2];
  49. #endif
  50.     char *to, c;
  51.     int  w, r, bytes_written;
  52.  
  53.     bytes_written = 0;
  54.     while (bytes_written < nbytes) {
  55.         w = 0;
  56.         to = buf;
  57.         while (w < BUFSIZ && bytes_written < nbytes) {
  58.             if ((c = *from++) == '\n') {
  59.                 *to++ = '\r'; *to++ = c;
  60.                 w += 2;
  61.             }
  62.             else {
  63.                 *to++ = c;
  64.                 w++;
  65.             }
  66.             bytes_written++;
  67.         }
  68.         if ((r = write(fd, buf, w)) != w)
  69.             return (r < 0) ? r : bytes_written - (w-r);
  70.     }
  71.     return bytes_written;
  72. }
  73.