Search code examples
c++cwinapistdio

Output of fprintf and WriteConsole happen in reverse order


I'm seeing strange behavior with console I/O in Windows. When I open a FILE * using CONOUT$ as the path, it's supposed to open the console's stdout. If I use that pointer for an fprintf and then a WriteConsole, you'd think the messages would come in respective order, but they actually happen in reverse.

Example code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <io.h>

int main(int argc, char *argv[]) {
  FILE *fout = fopen("CONOUT$", "w");
  fprintf(fout, "Hello world!\n");

  LPSTR goodbye = "Goodbye, cruel world!\n";
  DWORD length = strlen(goodbye);
  DWORD written;
  WriteConsole(_get_osfhandle(_fileno(fout)), goodbye, length, &written, NULL);

  return 0;
}

And the output:

Goodbye, cruel world!
Hello world!

Why is this? My guess is something to do with the way Win32 I/O functions and stdio synchronize (or rather, don't). I know C++ iostream needs to take special care to synchronize with stdio, so maybe Win32 doesn't do that?


Solution

  • This might have to do with some buffering stdio.h adds to output. Try adding a

    fflush(fout);
    

    after the fprintf. Alternatively you could try a

    setbuf(fout, null);
    

    to disable buffering for your output stream.

    As to the "bonus" (printf working correctly): Afaik stoutis usually set up in a way that it flushes automatically after each newline.