Defined in header <cstdio> | ||||
---|---|---|---|---|
|
Changes the the buffering mode of the given file stream stream
as indicated by the argument mode
. In addition,
- If if
buffer
is a null pointer, resizes of the internal buffer tosize
. - If
buffer
is not a null pointer, instructs the stream to use the user-provided buffer of sizesize
beginning atbuffer
. The stream must be closed (withfclose
) before the lifetime of the array pointed to bybuffer
ends. The contents of the array after a successful call tosetvbuf
are indeterminate and any attempt to use it is undefined behavior.
Parameters
stream | - | the file stream to set the buffer to or null pointer to change size and mode only | ||||||
buffer | - | pointer to a buffer for the stream to use | ||||||
mode | - | buffering mode to use. It can be one of the following values:
| ||||||
size | - | size of the buffer |
Return value
0
on success or nonzero on failure.
Notes
This function may only be used after stream
has been associated with an open file, but before any other operation (other than a failed call to std::setbuf
/std::setvbuf
).
Not all size
bytes will necessarily be used for buffering: the actual buffer size is usually rounded down to a multiple of 2, a multiple of page size, etc.
On many implementations, line buffering is only available for terminal input streams.
A common error is setting the buffer of stdin or stdout to an array whose lifetime ends before the program terminates:
1 2 3 4 | int main() { char buf[BUFSIZ]; std:: setbuf (stdin, buf); } // lifetime of buf ends, undefined behavior |
The default buffer size BUFSIZ
is expected to be the most efficient buffer size for file I/O on the implementation, but POSIX fstat often provides a better estimate.
Example
one use case for changing buffer size is when a better size is known.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> #include <cstdio> #include <stdlib.h> #include <sys/stat.h> int main() { std:: FILE * fp = std:: fopen ( "test.txt" , "r" ); if (!fp) { std:: perror ( "fopen" ); return 1; } struct stat stats; if (fstat(fileno(fp), &stats) == -1) { // POSIX only std:: perror ( "fstat" ); return 1; } std::cout << "BUFSIZ is " << BUFSIZ << ", but optimal block size is " << stats.st_blksize << '\n' ; if (std:: setvbuf (fp, NULL, _IOFBF, stats.st_blksize) != 0) { perror ( "setvbuf failed" ); // POSIX version sets errno return 1; } int ch; while ((ch=std:: fgetc (fp)) != EOF); // read entire file: use truss/strace to // observe the read(2) syscalls used } |
Possible output:
1 | BUFSIZ is 8192, but optimal block size is 65536 |
See also
sets the buffer for a file stream (function) | |
[virtual] | provides user-supplied buffer or turns this filebuf unbuffered (virtual protected member function of std::basic_filebuf ) |
C documentation for setvbuf |
Please login to continue.