std::setbuf(3)
π NAME π
okay so bestie, this is the std::setbuf page from the C++ Standard Libary manual (section 3) β and the NAME is literally std::setbuf - std::setbuf, which is giving βname so nice they said it twiceβ energy. π
Weβre gonna cover every detail, no cap, fr fr.
β¨ Synopsis β¨
Defined in header <cstdio>:
void setbuf( std::FILE* stream, char* buffer );
Sets the internal buffer to use for I/O operations performed on the C stream stream.
If buffer is not null, equivalent to std::setvbuf(stream, buffer, _IOFBF, BUFSIZ).
If buffer is null, equivalent to std::setvbuf(stream, nullptr, _IONBF, 0), which turns off buffering.
π Parameters π
streamβ the file stream to set the buffer to. This is the stream bestie whose buffering situation weβre changing.bufferβ pointer to a buffer for the stream to use. If a null pointer is supplied, the buffering is turned off. If not null, must be able to hold at leastBUFSIZcharacters. So like, size matters here, bestie.
πΈ Return value πΈ
(none)β no return value, periodt. π
π¦ Notes π¦
- If
BUFSIZis not the appropriate buffer size,std::setvbufcan be used to change it. Flexible queen behavior, iconic. std::setvbufshould also be used to detect errors, sincestd::setbufdoes not indicate success or failure. So if you need the error tea,std::setvbufis the one, ngl.- This function may only be used after
streamhas been associated with an open file, but before any other operation (other than a failed call tostd::setbuf/std::setvbuf). Timing is everything, bestie β highkey do not freestyle this. β¨ - A common error is setting the buffer of
stdinorstdoutto an array whose lifetime ends before the program terminates: not me seeing this exact footgun in the wild π
int main()
{
char buf[BUFSIZ];
std::setbuf(stdin, buf);
} // lifetime of buf ends, undefined behavior
π¨ That comment says undefined behavior, and it means it. Keep that buffer alive for the whole program β not the cute kind of βoopsβ, okay?
π₯ Example π₯
std::setbuf may be used to disable buffering on streams that require immediate output.
// Run this code
#include <chrono>
#include <cstdio>
#include <thread>
int main()
{
using namespace std::chrono_literals;
std::setbuf(stdout, nullptr); // unbuffered stdout
std::putchar('a'); // appears immediately on unbuffered stream
std::this_thread::sleep_for(1s);
std::putchar('b');
}
Output:
ab
π See also π
setvbufβ sets the buffer and its size for a file stream (function).- C documentation for
setbuf.
xoxo, your std::setbuf(3) bestie π β source/version http://cppreference.com, dated 2024.06.10. Mwah! π«Ά
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms