3 /* setvbuf( FILE *, char *, int, size_t )
5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
15 int setvbuf( struct _PDCLIB_file_t * _PDCLIB_restrict stream, char * _PDCLIB_restrict buf, int mode, size_t size )
20 /* When unbuffered I/O is requested, we keep the buffer anyway, as
21 we don't want to e.g. flush the stream for every character of a
27 if ( size > INT_MAX || size == 0 )
29 /* PDCLib only supports buffers up to INT_MAX in size. A size
30 of zero doesn't make sense.
36 /* User requested buffer size, but leaves it to library to
39 /* If current buffer is big enough for requested size, but not
40 over twice as big (and wasting memory space), we use the
41 current buffer (i.e., do nothing), to save the malloc() /
44 if ( ( stream->bufsize < size ) || ( stream->bufsize > ( size << 1 ) ) )
46 /* Buffer too small, or much too large - allocate. */
47 if ( ( buf = (char *) malloc( size ) ) == NULL )
49 /* Out of memory error. */
52 /* This buffer must be free()d on fclose() */
53 stream->status |= _PDCLIB_FREEBUFFER;
57 stream->bufsize = size;
60 /* If mode is something else than _IOFBF, _IOLBF or _IONBF -> exit */
63 /* Deleting current buffer mode */
64 stream->status &= ~( _IOFBF | _IOLBF | _IONBF );
65 /* Set user-defined mode */
66 stream->status |= mode;
73 #include <_PDCLIB_test.h>
77 #define BUFFERSIZE 500
82 char buffer[ BUFFERSIZE ];
84 /* full buffered, user-supplied buffer */
85 TESTCASE( ( fh = tmpfile() ) != NULL );
86 TESTCASE( setvbuf( fh, buffer, _IOFBF, BUFFERSIZE ) == 0 );
87 TESTCASE( fh->buffer == buffer );
88 TESTCASE( fh->bufsize == BUFFERSIZE );
89 TESTCASE( ( fh->status & ( _IOFBF | _IONBF | _IOLBF ) ) == _IOFBF );
90 TESTCASE( fclose( fh ) == 0 );
91 /* line buffered, lib-supplied buffer */
92 TESTCASE( ( fh = tmpfile() ) != NULL );
93 TESTCASE( setvbuf( fh, NULL, _IOLBF, BUFFERSIZE ) == 0 );
94 TESTCASE( fh->buffer != NULL );
95 TESTCASE( fh->bufsize == BUFFERSIZE );
96 TESTCASE( ( fh->status & ( _IOFBF | _IONBF | _IOLBF ) ) == _IOLBF );
97 TESTCASE( fclose( fh ) == 0 );
98 /* not buffered, user-supplied buffer */
99 TESTCASE( ( fh = tmpfile() ) != NULL );
100 TESTCASE( setvbuf( fh, buffer, _IONBF, BUFFERSIZE ) == 0 );
101 TESTCASE( ( fh->status & ( _IOFBF | _IONBF | _IOLBF ) ) == _IONBF );
102 TESTCASE( fclose( fh ) == 0 );
104 puts( " NOTEST setvbuf() test driver is PDCLib-specific." );