Search code examples
cwindowsmingw-w64flushmsys2

Why does printf() with \n still not flush on Windows?


My Windows program (compiled using MSYS2 MINGW64) outputs its stdout data in large blocks. A printf() call with a \n doesn't correctly flush the output.

As a variation of this question, under what conditions does printf() NOT flush?


As an example, the following code outputs in blocks on MSYS2 MINGW64:

#include <stdio.h>

int main() {
        while(1) {
                printf("test\n");
                Sleep(1);
        }
        return 0;
}

Solution

  • On Windows there's no line buffering, only no and full buffering

    • _IOLBF
      • For some systems, this provides line buffering. However, for Win32, the behavior is the same as _IOFBF - Full Buffering.

    setvbuf

    Wait for a while until the buffer is full, or flush the buffer yourself. Alternatively you can decrease the buffer size with setvbuf() so that it flushes more frequently