xref: /minix3/lib/libc/stdio/setvbuf.c (revision 9a21d1a2fdca366d7697d6ecbfe4ed6d5851f9c7)
1 /*
2  * setbuf.c - control buffering of a stream
3  */
4 
5 #include	<stdio.h>
6 #include	<stdlib.h>
7 #include	"loc_incl.h"
8 
9 extern void (*_clean)(void);
10 
11 int
12 setvbuf(register FILE *stream, char *buf, int mode, size_t size)
13 {
14 	int retval = 0;
15 
16 	_clean = __cleanup;
17 	if (mode != _IOFBF && mode != _IOLBF && mode != _IONBF)
18 		return EOF;
19 
20 	if (stream->_buf && io_testflag(stream,_IOMYBUF) )
21 		free((void *)stream->_buf);
22 
23 	stream->_flags &= ~(_IOMYBUF | _IONBF | _IOLBF);
24 
25 	if (buf && size <= 0) retval = EOF;
26 	if (!buf && (mode != _IONBF)) {
27 		if (size <= 0 || (buf = (char *) malloc(size)) == NULL) {
28 			retval = EOF;
29 		} else {
30 			stream->_flags |= _IOMYBUF;
31 		}
32 	}
33 
34 	stream->_buf = (unsigned char *) buf;
35 
36 	stream->_count = 0;
37 	stream->_flags |= mode;
38 	stream->_ptr = stream->_buf;
39 
40 	if (!buf) {
41 		stream->_bufsiz = 1;
42 	} else {
43 		stream->_bufsiz = size;
44 	}
45 
46 	return retval;
47 }
48