Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatically buffer os.Stdout

Tags:

go

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?

like image 248
William Pursell Avatar asked Nov 16 '12 18:11

William Pursell


People also ask

What is buffering stdout?

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.

What is OS stdout?

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.

Is stdout buffered in C?

In C, file output is block buffered. Output to stdout is line buffered. The stderr device is unbuffered.


1 Answers

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.

like image 185
Stephen Weinberg Avatar answered Oct 17 '22 08:10

Stephen Weinberg