home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / ansi / stdio / flsbuf.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-15  |  2.1 KB  |  100 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  3. #include <libc/stubs.h>
  4. #include <stdio.h>
  5. #include <sys/types.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <go32.h>
  9. #include <libc/file.h>
  10. #include <io.h>
  11.  
  12. int
  13. _flsbuf(int c, FILE *f)
  14. {
  15.   char *base;
  16.   int n, rn;
  17.   char c1;
  18.   int size;
  19.  
  20.   if (f->_flag & _IORW)
  21.   {
  22.     f->_flag |= _IOWRT;
  23.     f->_flag &= ~(_IOEOF|_IOREAD);
  24.   }
  25.  
  26.   if ((f->_flag&_IOWRT)==0)
  27.     return EOF;
  28.  
  29.   /* if the buffer is not yet allocated, allocate it */
  30.   if ((base = f->_base) == NULL && (f->_flag & _IONBF) == 0)
  31.   {
  32.     size = _go32_info_block.size_of_transfer_buffer;
  33.     if ((f->_base = base = malloc (size)) == NULL)
  34.     {
  35.       f->_flag |= _IONBF;
  36.       f->_flag &= ~(_IOFBF|_IOLBF);
  37.     }
  38.     else
  39.     {
  40.       f->_flag |= _IOMYBUF;
  41.       f->_cnt = f->_bufsiz = size;
  42.       f->_ptr = base;
  43.       rn = 0;
  44.       if (f == stdout && isatty (fileno (stdout)))
  45.     f->_flag |= _IOLBF;
  46.     }
  47.   }
  48.  
  49.   if (f->_flag & _IOLBF)
  50.   {
  51.     /* in line-buffering mode we get here on each character */
  52.     *f->_ptr++ = c;
  53.     rn = f->_ptr - base;
  54.     if (c == '\n' || rn >= f->_bufsiz)
  55.     {
  56.       /* time for real flush */
  57.       f->_ptr = base;
  58.       f->_cnt = 0;
  59.     }
  60.     else
  61.     {
  62.       /* we got here because _cnt is wrong, so fix it */
  63.       /* Negative _cnt causes all output functions
  64.     to call _flsbuf for each character, thus realizing line-buffering */
  65.       f->_cnt = -rn;
  66.       return c;
  67.     }
  68.   }
  69.   else if (f->_flag & _IONBF)
  70.   {                   
  71.     c1 = c;           
  72.     rn = 1;           
  73.     base = &c1;       
  74.     f->_cnt = 0;      
  75.   }                   
  76.   else /* _IOFBF */
  77.   {
  78.     rn = f->_ptr - base;
  79.     f->_ptr = base;
  80.     f->_cnt = f->_bufsiz;
  81.   }
  82.   while (rn > 0)
  83.   {
  84.     n = _write(fileno(f), base, rn);
  85.     if (n <= 0)
  86.     {
  87.       f->_flag |= _IOERR;
  88.       return EOF;
  89.     }
  90.     rn -= n;
  91.     base += n;
  92.   }
  93.   if ((f->_flag&(_IOLBF|_IONBF)) == 0)
  94.   {
  95.     f->_cnt--;
  96.     *f->_ptr++ = c;
  97.   }
  98.   return c;
  99. }
  100.