Force the terminal output buffer to flush

979 views Asked by At

Writing a CLI tool in D, I have a progress counter, which is a loop, and print the next number preceded with a \r.

Here is a minimal example that shows the problem

import std.stdio;
import core.thread;

void main(string[] args) {
    for (int i = 0; i < 10000; i++) {
        write("\r", i);
        Thread.sleep(msecs(1));
    }
}

I have noticed that, at least the mac terminal, buffers the output, which is flushed once a newline is printed, or a certain amount of characters has been printed.

For me, this means that the counter laggy and sporadically goes up.

My question is, How do I force flush the output buffer, without printing a newline?

2

There are 2 answers

0
weltensturm On BEST ANSWER

By 'clearing the buffer' you probably mean flushing. stdout.flush; should do the trick.

Clearing normally refers to removing all output from the console to get a clean window.

0
rlonstein On

In addition to weltensturm's answer to call stdout.flush periodically, you may try to manually set buffering with

  stdout.setvbuf(0, _IOLBF);

See IEEE Std 1003.1, 2013 - setvbuf (or your local manpages) for an overview.