std::setbuf(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ 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 least BUFSIZ characters. So like, size matters here, bestie.

🌸 Return value 🌸

  • (none) β€” no return value, periodt. πŸ’€

πŸ¦‹ Notes πŸ¦‹

  • If BUFSIZ is not the appropriate buffer size, std::setvbuf can be used to change it. Flexible queen behavior, iconic.
  • std::setvbuf should also be used to detect errors, since std::setbuf does not indicate success or failure. So if you need the error tea, std::setvbuf is the one, ngl.
  • 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). Timing is everything, bestie β€” highkey do not freestyle this. ✨
  • A common error is setting the buffer of stdin or stdout to 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