home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / CLIPPER / MISC / EMXLIB8F.ZIP / EMX / LIB / IO / WRITE.C < prev   
Encoding:
C/C++ Source or Header  |  1993-01-02  |  1.7 KB  |  72 lines

  1. /* write.c (emx+gcc) -- Copyright (c) 1990-1993 by Eberhard Mattes */
  2.  
  3. #include <sys/emx.h>
  4. #include <io.h>
  5. #include <errno.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8.  
  9. #define CTRL_Z 0x1a
  10.  
  11. #define BEGIN do {
  12. #define END   } while (0)
  13.  
  14. #define WRTBUF \
  15.   BEGIN n = __write (handle, tmp, buf_cnt); \
  16.     if (n < 0) goto error;              \
  17.     out_cnt += n;                       \
  18.     if (n != buf_cnt) {errno = ENOSPC; return (-1);} \
  19.     buf_cnt = 0;                        \
  20.   END
  21.  
  22. int write (int handle, const void *buf, size_t nbyte)
  23. {
  24.   int out_cnt, lf_cnt, i, n, buf_cnt;
  25.   const char *src, *p;
  26.   char tmp[1024];
  27.  
  28.   if (handle < 0 || handle >= _nfiles)
  29.     {
  30.       errno = EBADF; return (-1);
  31.     }
  32.   if (_files[handle] & O_APPEND)
  33.     __lseek (handle, 0L, SEEK_END);
  34.   if (nbyte == 0)                 /* Avoid truncation of file */
  35.     return (0);
  36.   src = buf;
  37.   if (_files[handle] & O_TEXT)
  38.     {
  39.       out_cnt = lf_cnt = 0;
  40.       buf_cnt = 0;
  41.       p = memchr (src, '\n', nbyte);
  42.       if (p == NULL)
  43.         goto write_bin;
  44.       for (i = 0; i < nbyte; ++i)
  45.         {
  46.           if (src[i] == '\n')
  47.             {
  48.               if (buf_cnt >= sizeof (tmp)) WRTBUF;
  49.               tmp[buf_cnt++] = '\r';
  50.               ++lf_cnt;
  51.             }
  52.           if (buf_cnt >= sizeof (tmp)) WRTBUF;
  53.           tmp[buf_cnt++] = src[i];
  54.         }
  55.       if (buf_cnt != 0) WRTBUF;
  56.       return (out_cnt - lf_cnt);
  57.     }
  58.   
  59. write_bin:
  60.   n = __write (handle, src, nbyte);
  61.   if (n < 0) goto error;
  62.   if (n == 0 && !((_files[handle] & F_DEV) && *src == CTRL_Z))
  63.     {
  64.       errno = ENOSPC;
  65.       return (-1);
  66.     }
  67.   return (n);
  68.   
  69. error:
  70.   return (-1);
  71. }
  72.