Mon Dec 18 13:40:37 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu>
[glibc.git] / stdio / setvbuf.c
blob6bfe829d1d91dbdc32b368331eaf99bef718e65e
1 /* Copyright (C) 1991, 1993, 1995 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA. */
19 #include <ansidecl.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <errno.h>
26 /* Make STREAM use the buffering method given in MODE.
27 If MODE indicates full or line buffering, use BUF,
28 a buffer of SIZE bytes; if BUF is NULL, malloc a buffer. */
29 int
30 DEFUN(setvbuf, (stream, buf, mode, size),
31 FILE *stream AND char *buf AND int mode AND size_t size)
33 if (!__validfp(stream))
35 errno = EINVAL;
36 return EOF;
39 /* The ANSI standard says setvbuf can only be called before any I/O is done,
40 but we allow it to replace an old buffer, flushing it first. */
41 if (stream->__buffer != NULL)
43 (void) fflush(stream);
44 /* Free the old buffer if it was malloc'd. */
45 if (!stream->__userbuf)
46 free(stream->__buffer);
49 stream->__get_limit = stream->__put_limit = NULL;
50 stream->__bufp = stream->__buffer = NULL;
51 stream->__userbuf = stream->__linebuf = stream->__linebuf_active = 0;
53 switch (mode)
55 default:
56 errno = EINVAL;
57 return EOF;
58 case _IONBF: /* Unbuffered. */
59 stream->__buffer = NULL;
60 stream->__bufsize = 0;
61 stream->__userbuf = 1;
62 break;
63 case _IOLBF: /* Line buffered. */
64 stream->__linebuf = 1;
65 case _IOFBF: /* Fully buffered. */
66 if (size == 0)
68 errno = EINVAL;
69 return EOF;
71 stream->__bufsize = size;
72 if (buf != NULL)
73 stream->__userbuf = 1;
74 else if ((buf = (char *) malloc(size)) == NULL)
75 return EOF;
76 stream->__buffer = buf;
77 break;
80 stream->__bufp = stream->__buffer;
81 stream->__get_limit = stream->__buffer;
82 /* The next output operation will prime the stream for writing. */
83 stream->__put_limit = stream->__buffer;
85 return 0;