Update.
[glibc.git] / stdio / setvbuf.c
blob079bbb30a2de578e838bdf4209bda1a732ea818c
1 /* Copyright (C) 1991, 1993, 1995, 1996, 1997 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 not,
16 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 Boston, MA 02111-1307, USA. */
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <errno.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 setvbuf (stream, buf, mode, size)
30 FILE *stream;
31 char *buf;
32 int mode;
33 size_t size;
35 if (!__validfp (stream))
37 __set_errno (EINVAL);
38 return EOF;
41 /* The ANSI standard says setvbuf can only be called before any I/O is done,
42 but we allow it to replace an old buffer, flushing it first. */
43 if (stream->__buffer != NULL)
45 (void) fflush (stream);
46 /* Free the old buffer if it was malloc'd. */
47 if (!stream->__userbuf)
48 free(stream->__buffer);
51 stream->__get_limit = stream->__put_limit = NULL;
52 stream->__bufp = stream->__buffer = NULL;
53 stream->__userbuf = stream->__linebuf = stream->__linebuf_active = 0;
55 switch (mode)
57 default:
58 __set_errno (EINVAL);
59 return EOF;
60 case _IONBF: /* Unbuffered. */
61 stream->__buffer = NULL;
62 stream->__bufsize = 0;
63 stream->__userbuf = 1;
64 break;
65 case _IOLBF: /* Line buffered. */
66 stream->__linebuf = 1;
67 case _IOFBF: /* Fully buffered. */
68 if (size == 0)
70 __set_errno (EINVAL);
71 return EOF;
73 stream->__bufsize = size;
74 if (buf != NULL)
75 stream->__userbuf = 1;
76 else if ((buf = (char *) malloc (size)) == NULL)
77 return EOF;
78 stream->__buffer = buf;
79 break;
82 stream->__bufp = stream->__buffer;
83 stream->__get_limit = stream->__buffer;
84 /* The next output operation will prime the stream for writing. */
85 stream->__put_limit = stream->__buffer;
87 return 0;