os.Stdout.Write()
is an unbuffered write. To get a buffered write, one can use the following:
f := bufio.NewWriter(os.Stdout)
f.Write(b)
Question:
Is there a more idiomatic way to get buffered output?
By default writes to stdout pass through a 4096 byte buffer, unless stdout happens to be a terminal/tty in which case it is line buffered. Hence the inconsistency between the immediate output when your program is writing to the terminal and the delayed output when it is writing to a pipe or file.
Stdout, also known as standard output, is the default file descriptor where a process can write output. In Unix-like operating systems, such as Linux, macOS X, and BSD, stdout is defined by the POSIX standard. Its default file descriptor number is 1. In the terminal, standard output defaults to the user's screen.
In C, file output is block buffered. Output to stdout is line buffered. The stderr device is unbuffered.
No, that is the most idiomatic way to buffer writes to Stdout. In many cases, you will want to do also add a defer:
f := bufio.NewWriter(os.Stdout)
defer f.Flush()
f.Write(b)
This will ensure that the buffer is flushed when you return from the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With