branch update for HEAD-2003021201
[reactos.git] / lib / crtdll / stdio / setvbuf.c
1 /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
2 /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
3 /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
4 #include <msvcrt/stdio.h>
5 #include <msvcrt/stdlib.h>
6 #include <msvcrt/io.h>
7 #include <msvcrt/errno.h>
8 #include <msvcrt/internal/file.h>
9
10
11 int setvbuf(FILE *f, char *buf, int type, size_t len)
12 {
13   int mine=0;
14   if (!__validfp (f) ) {
15         __set_errno (EINVAL);
16         return 0;
17   }
18   if ( f->_base != NULL )
19         fflush(f);
20   switch (type)
21   {
22   case _IOFBF:
23   case _IOLBF:
24     if (len <= 0) {
25         __set_errno (EINVAL);
26         return EOF;
27     }
28     if (buf == 0)
29     {
30       buf = (char *)malloc(len+1);
31       if (buf == NULL) {
32         __set_errno (ENOMEM);
33         return -1;
34       }
35       mine = 1;
36     }
37     /* FALLTHROUGH */
38   case _IONBF:
39     if (f->_base != NULL && f->_flag & _IOMYBUF)
40       free(f->_base);
41     f->_cnt = 0;
42
43     f->_flag &= ~(_IONBF|_IOFBF|_IOLBF|_IOUNGETC);
44     f->_flag |= type;
45     if (type != _IONBF)
46     {
47       if (mine)
48         f->_flag |= _IOMYBUF;
49       f->_ptr = f->_base = buf;
50       f->_bufsiz = len;
51     }
52     else
53     {
54       f->_base = 0;
55       f->_bufsiz = 0;
56     }
57     return 0;
58   default:
59       __set_errno (EINVAL);
60       return EOF;
61   }
62 }