home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / zip / gnu / mntlib16.lzh / MNTLIB16 / TEXTIO.C < prev    next >
C/C++ Source or Header  |  1993-07-29  |  1KB  |  68 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.  
  9. #include <stdio.h>
  10. #include <unistd.h>
  11.  
  12. int
  13. _text_read(fd, buf, nbytes)
  14.     int fd;
  15.     char *buf;
  16.     int nbytes;
  17. {
  18.     char *to, *from;
  19.     int  r;
  20.  
  21. _again:
  22.     r = read(fd, buf, nbytes);
  23.     if (r <= 0)
  24.         return r;
  25.     nbytes = r;
  26.     to = from = buf;
  27.     while (r-- > 0) {
  28.         if (*from == '\r') {
  29.             from++; nbytes--;
  30.         }
  31.         else
  32.             *to++ = *from++;
  33.     }
  34.     if (nbytes == 0)
  35.         goto _again;
  36.     return nbytes;
  37. }
  38.  
  39. int
  40. _text_write(fd, from, nbytes)
  41.     int fd;
  42.     char *from;
  43.     int nbytes;
  44. {
  45.     char buf[BUFSIZ+2], *to, c;
  46.     int  w, r, bytes_written;
  47.  
  48.     bytes_written = 0;
  49.     while (bytes_written < nbytes) {
  50.         w = 0;
  51.         to = buf;
  52.         while (w < BUFSIZ && bytes_written < nbytes) {
  53.             if ((c = *from++) == '\n') {
  54.                 *to++ = '\r'; *to++ = c;
  55.                 w += 2;
  56.             }
  57.             else {
  58.                 *to++ = c;
  59.                 w++;
  60.             }
  61.             bytes_written++;
  62.         }
  63.         if ((r = write(fd, buf, w)) != w)
  64.             return (r < 0) ? r : bytes_written - (w-r);
  65.     }
  66.     return bytes_written;
  67. }
  68.