xref: /original-bsd/lib/libc/stdio/wsetup.c (revision c3e32dec)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Chris Torek.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)wsetup.c	8.1 (Berkeley) 06/04/93";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include "local.h"
18 
19 /*
20  * Various output routines call wsetup to be sure it is safe to write,
21  * because either _flags does not include __SWR, or _buf is NULL.
22  * _wsetup returns 0 if OK to write, nonzero otherwise.
23  */
24 __swsetup(fp)
25 	register FILE *fp;
26 {
27 	/* make sure stdio is set up */
28 	if (!__sdidinit)
29 		__sinit();
30 
31 	/*
32 	 * If we are not writing, we had better be reading and writing.
33 	 */
34 	if ((fp->_flags & __SWR) == 0) {
35 		if ((fp->_flags & __SRW) == 0)
36 			return (EOF);
37 		if (fp->_flags & __SRD) {
38 			/* clobber any ungetc data */
39 			if (HASUB(fp))
40 				FREEUB(fp);
41 			fp->_flags &= ~(__SRD|__SEOF);
42 			fp->_r = 0;
43 			fp->_p = fp->_bf._base;
44 		}
45 		fp->_flags |= __SWR;
46 	}
47 
48 	/*
49 	 * Make a buffer if necessary, then set _w.
50 	 */
51 	if (fp->_bf._base == NULL)
52 		__smakebuf(fp);
53 	if (fp->_flags & __SLBF) {
54 		/*
55 		 * It is line buffered, so make _lbfsize be -_bufsize
56 		 * for the putc() macro.  We will change _lbfsize back
57 		 * to 0 whenever we turn off __SWR.
58 		 */
59 		fp->_w = 0;
60 		fp->_lbfsize = -fp->_bf._size;
61 	} else
62 		fp->_w = fp->_flags & __SNBF ? 0 : fp->_bf._size;
63 	return (0);
64 }
65