Force write to write to console

Peter C peterc at gmail.com
Sun Dec 7 23:19:52 UTC 2025


On Saturday, 6 December 2025 at 21:25:27 UTC, Brother Bill wrote:
> ```
> write("foo"); // writes to the console, but it doesn't display 
> yet.
> writeln;      // Now it displays, with a new line.
> ```
>
> How to force writing to the console after ```write("foo");```
>
> I am doing this for a tutorial video, and want the 
> ```write("foo");```
> to immediately write to the console.

// A newline will force a flush: write("foo\n"); // appears 
immediately

// You could also do it in an 'unsafe' C way, by disabling 
buffering.
// D makes it ever so easy to simply drop into C mode code

// Or make a call to stdout.flush() - as others have noted 
already.

module myModule;
import std.stdio : write;
import core.thread;
import core.stdc.stdio;
@safe:
private:

@trusted void main()
{
     // Disable buffering
     setvbuf(core.stdc.stdio.stdout, null, _IONBF, 0); // NOTE: 
Calls into C are not @safe

     write("foo"); // appears immediately
     Thread.sleep(3.seconds);

     // NOTE: Toggling buffering modes mid-program is unwise ;-)
     // So pick one mode at startup, or use stdout.flush()
}


More information about the Digitalmars-d-learn mailing list