Changes the buffering mode of the given file stream stream as indicated by the argument mode. In addition,
â0â on success or nonzero on failure.
[edit] NotesThis 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:
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.
One use case for changing buffer size is when a better size is known.
#include <cstdio> #include <cstdlib> #include <iostream> #include <sys/stat.h> int main() { std::FILE* fp = std::fopen("/tmp/test.txt", "w+"); if (!fp) { std::perror("fopen"); return EXIT_FAILURE; } struct stat stats; if (fstat(fileno(fp), &stats) == -1) // POSIX only { std::perror("fstat"); return EXIT_FAILURE; } std::cout << "BUFSIZ is " << BUFSIZ << ", but optimal block size is " << stats.st_blksize << '\n'; if (std::setvbuf(fp, nullptr, _IOFBF, stats.st_blksize) != 0) { std::perror("setvbuf failed"); // POSIX version sets errno return EXIT_FAILURE; } // Read entire file: use truss/strace to observe the read(2) syscalls used for (int ch; (ch = std::fgetc(fp)) != EOF;) {} std::fclose(fp); return EXIT_SUCCESS; }
Possible output:
BUFSIZ is 8192, but optimal block size is 65536[edit] See also sets the buffer for a file stream
std::basic_filebuf<CharT,Traits>
) [edit]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4