initial import
[glibc.git] / stdio / setvbuf.c
blob8c33386610b6fda906a9634ce6302cebc8b3ccdc
1 /* Copyright (C) 1991, 1993 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>
25 /* Make STREAM use the buffering method given in MODE.
26 If MODE indicates full or line buffering, use BUF,
27 a buffer of SIZE bytes; if BUF is NULL, malloc a buffer. */
28 int
29 DEFUN(setvbuf, (stream, buf, mode, size),
30 FILE *stream AND char *buf AND int mode AND size_t size)
32 if (!__validfp(stream))
34 errno = EINVAL;
35 return EOF;
38 /* The ANSI standard says setvbuf can only be called before any I/O is done,
39 but we allow it to replace an old buffer, flushing it first. */
40 if (stream->__buffer != NULL)
42 (void) fflush(stream);
43 /* Free the old buffer if it was malloc'd. */
44 if (!stream->__userbuf)
45 free(stream->__buffer);
48 stream->__get_limit = stream->__put_limit = NULL;
49 stream->__bufp = stream->__buffer = NULL;
50 stream->__userbuf = stream->__linebuf = stream->__linebuf_active = 0;
52 switch (mode)
54 default:
55 errno = EINVAL;
56 return EOF;
57 case _IONBF: /* Unbuffered. */
58 stream->__buffer = NULL;
59 stream->__bufsize = 0;
60 stream->__userbuf = 1;
61 break;
62 case _IOLBF: /* Line buffered. */
63 stream->__linebuf = 1;
64 case _IOFBF: /* Fully buffered. */
65 if (size == 0)
67 errno = EINVAL;
68 return EOF;
70 stream->__bufsize = size;
71 if (buf != NULL)
72 stream->__userbuf = 1;
73 else if ((buf = (char *) malloc(size)) == NULL)
74 return EOF;
75 stream->__buffer = buf;
76 break;
79 stream->__bufp = stream->__buffer;
80 stream->__get_limit = stream->__buffer;
81 /* The next output operation will prime the stream for writing. */
82 stream->__put_limit = stream->__buffer;
84 return 0;