1 /* No user fns here. Pesch 15apr92. */ 2 3 /* 4 * Copyright (c) 1990 The Regents of the University of California. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms are permitted 8 * provided that the above copyright notice and this paragraph are 9 * duplicated in all such forms and that any documentation, 10 * advertising materials, and other materials related to such 11 * distribution and use acknowledge that the software was developed 12 * by the University of California, Berkeley. The name of the 13 * University may not be used to endorse or promote products derived 14 * from this software without specific prior written permission. 15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED 17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 18 */ 19 20 #if defined(LIBC_SCCS) && !defined(lint) 21 static char sccsid[] = "%W% (Berkeley) %G%"; 22 #endif /* LIBC_SCCS and not lint */ 23 24 #include <stdio.h> 25 #include "local.h" 26 #include "fvwrite.h" 27 28 /* 29 * Write the given character into the (probably full) buffer for 30 * the given file. Flush the buffer out if it is or becomes full, 31 * or if c=='\n' and the file is line buffered. 32 */ 33 34 int 35 __swbuf (c, fp) 36 register int c; 37 register FILE *fp; 38 { 39 register int n; 40 41 /* Ensure stdio has been initialized. */ 42 43 CHECK_INIT (fp); 44 45 /* 46 * In case we cannot write, or longjmp takes us out early, 47 * make sure _w is 0 (if fully- or un-buffered) or -_bf._size 48 * (if line buffered) so that we will get called again. 49 * If we did not do this, a sufficient number of putc() 50 * calls might wrap _w from negative to positive. 51 */ 52 53 fp->_w = fp->_lbfsize; 54 if (cantwrite (fp)) 55 return EOF; 56 c = (unsigned char) c; 57 58 /* 59 * If it is completely full, flush it out. Then, in any case, 60 * stuff c into the buffer. If this causes the buffer to fill 61 * completely, or if c is '\n' and the file is line buffered, 62 * flush it (perhaps a second time). The second flush will always 63 * happen on unbuffered streams, where _bf._size==1; fflush() 64 * guarantees that putc() will always call wbuf() by setting _w 65 * to 0, so we need not do anything else. 66 */ 67 68 n = fp->_p - fp->_bf._base; 69 if (n >= fp->_bf._size) 70 { 71 if (fflush (fp)) 72 return EOF; 73 n = 0; 74 } 75 fp->_w--; 76 *fp->_p++ = c; 77 if (++n == fp->_bf._size || (fp->_flags & __SLBF && c == '\n')) 78 if (fflush (fp)) 79 return EOF; 80 return c; 81 } 82