]> pd.if.org Git - pdclib/blob - functions/stdio/setvbuf.c
Added setvbuf().
[pdclib] / functions / stdio / setvbuf.c
1 /* $Id$ */
2
3 /* setvbuf( FILE *, char *, int, size_t )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #ifndef REGTEST
13
14 int setvbuf( struct _PDCLIB_file_t * _PDCLIB_restrict stream, char * _PDCLIB_restrict buf, int mode, size_t size )
15 {
16     /* Only allowed on "virgin" streams (i.e., before first I/O occurs), and
17        a valid value for mode.
18     */
19     if ( ( ! stream->status & _PDCLIB_VIRGINSTR ) ||
20          ( ( mode != _IOFBF ) && ( mode != _IOLBF ) && ( mode != _IONBF ) ) )
21     {
22         return -1;
23     }
24     /* If a buffer is provided by user... */
25     if ( buf != NULL )
26     {
27         /* ...do not free it in library functions like fclose(), freopen(). */
28         stream->status &= ~_PDCLIB_LIBBUFFER;
29     }
30     /* If no buffer is provided by user, but required... */
31     else if ( mode != _IONBF )
32     {
33         /* Since setvbuf() may be called (successfully) on a stream only once,
34            the stream's buffer at this point should *always* be that allocated
35            by fopen(), but better make sure.
36         */
37         if ( ! ( stream->status & _PDCLIB_LIBBUFFER ) )
38         {
39             return -1;
40         }
41         /* Drop old buffer, allocate new one of requested size (unless that is
42            equal to BUFSIZ, in which case we can use the one already allocated
43            by fopen().)
44         */
45         if ( size != BUFSIZ )
46         {
47             if ( ( buf = malloc( size ) ) == NULL )
48             {
49                 return -1;
50             }
51             free( stream->buffer );
52         }
53     }
54     /* Applying new settings to stream. */
55     stream->status &= ~( _IOFBF | _IOLBF | _IONBF );
56     stream->status |= mode;
57     stream->buffer = buf;
58     stream->bufsize = size;
59     stream->status &= ~_PDCLIB_VIRGINSTR;
60     return 0;
61 }
62
63 #endif
64
65 #ifdef TEST
66 #include <_PDCLIB_test.h>
67
68 int main( void )
69 {
70 #ifndef REGTEST
71     TESTCASE( NO_TESTDRIVER );
72 #else
73     puts( " NOTEST setvbuf() test driver is PDCLib-specific." );
74 #endif
75     return TEST_RESULTS;
76 }
77
78 #endif