1 /* No user fns here. Pesch 15apr92. */
2 
3 /*
4  * Copyright (c) 1990, 2007 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  * and/or 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 #define _DEFAULT_SOURCE
21 #include <_ansi.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include "local.h"
26 
27 /*
28  * Various output routines call wsetup to be sure it is safe to write,
29  * because either _flags does not include __SWR, or _buf is NULL.
30  * _wsetup returns 0 if OK to write, nonzero and set errno otherwise.
31  */
32 
33 int
_swsetup(register FILE * fp)34 _swsetup (
35        register FILE * fp)
36 {
37   /* Make sure stdio is set up.  */
38 
39   CHECK_INIT (_REENT, fp);
40 
41   /*
42    * If we are not writing, we had better be reading and writing.
43    */
44 
45   if ((fp->_flags & __SWR) == 0)
46     {
47       if ((fp->_flags & __SRW) == 0)
48         {
49 	  _REENT_ERRNO(ptr) = EBADF;
50 	  fp->_flags |= __SERR;
51 	  return EOF;
52         }
53       if (fp->_flags & __SRD)
54 	{
55 	  /* clobber any ungetc data */
56 	  if (HASUB (fp))
57 	    FREEUB (ptr, fp);
58 	  fp->_flags &= ~(__SRD | __SEOF);
59 	  fp->_r = 0;
60 	  fp->_p = fp->_bf._base;
61 	}
62       fp->_flags |= __SWR;
63     }
64 
65   /*
66    * Make a buffer if necessary, then set _w.
67    * A string I/O file should not explicitly allocate a buffer
68    * unless asprintf is being used.
69    */
70   if (fp->_bf._base == NULL
71         && (!(fp->_flags & __SSTR) || (fp->_flags & __SMBF)))
72     _smakebuf ( fp);
73 
74   if (fp->_flags & __SLBF)
75     {
76       /*
77        * It is line buffered, so make _lbfsize be -_bufsize
78        * for the putc() macro.  We will change _lbfsize back
79        * to 0 whenever we turn off __SWR.
80        */
81       fp->_w = 0;
82       fp->_lbfsize = -fp->_bf._size;
83     }
84   else
85     fp->_w = fp->_flags & __SNBF ? 0 : fp->_bf._size;
86 
87   if (!fp->_bf._base && (fp->_flags & __SMBF))
88     {
89       /* __smakebuf_r set errno, but not flag */
90       fp->_flags |= __SERR;
91       return EOF;
92     }
93   return 0;
94 }
95