__putc.c (1133B)
1 #include <errno.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 #include "../libc.h" 6 7 int 8 fflush(FILE *fp) 9 { 10 int err; 11 12 if (fp) 13 return _flsbuf(fp); 14 15 err = 0; 16 for (fp = __iob; fp < &__iob[FOPEN_MAX]; ++fp) { 17 if ((fp->flags & _IOWRITE) == 0 && _flsbuf(fp)) 18 err = EOF; 19 } 20 return err; 21 } 22 23 static void 24 cleanup(void) 25 { 26 fflush(NULL); 27 } 28 29 int 30 __putc(int ch, FILE *fp) 31 { 32 static int first = 1; 33 34 if (fp->flags & _IOERR) 35 return EOF; 36 37 if (fp->flags & _IOREAD) { 38 fp->flags |= _IOERR; 39 errno = EBADF; 40 return EOF; 41 } 42 43 if (fp->flags & _IOSTRG) { 44 fp->flags |= _IOERR; 45 return EOF; 46 } 47 48 if (fp->buf == NULL && _allocbuf(fp)) 49 return EOF; 50 51 if (first) { 52 if (atexit(cleanup)) { 53 fp->flags |= _IOERR; 54 errno = ENOMEM; 55 return EOF; 56 } 57 first = 0; 58 } 59 60 if (fp->flags & _IOLBF) { 61 if (fp->wp == fp->lp && _flsbuf(fp)) 62 return EOF; 63 *fp->wp++ = ch; 64 if (ch == '\n' && _flsbuf(fp)) 65 return EOF; 66 } else if (fp->flags & _IOFBF) { 67 if (_flsbuf(fp)) 68 return EOF; 69 *fp->wp++ = ch; 70 fp->rp = fp->buf + fp->len; 71 } else { 72 *fp->wp++ = ch; 73 if (_flsbuf(fp)) 74 return EOF; 75 } 76 77 fp->flags |= _IOWRITE; 78 return ch & 0xFF; 79 }