cwinapiconsolewindows-console

Why can't I redirect output from WriteConsole?


In the following program I print to the console using two different functions

#include <windows.h>

int main() {
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD byteswritten;
    WriteConsole(h, "WriteConsole", 12, &byteswritten, NULL);
    WriteFile(h, "WriteFile", 9, &byteswritten, NULL);
}

If when I execute this program and redirect it's output using a > out.txt or a 1> out.txt nothing gets printed to the console (as expected) but the contents of out.txt are only

WriteFile

What is different between the two that allows calls to WriteFile to be redirected to the file and calls to WriteConsole to go to ... nowhere

Tested with gcc and msvc on windows 10


Solution

  • WriteConsole only works with console screen handles, not files nor pipes.

    If you are only writing ASCII content you can use WriteFile for everything.

    If you need to write Unicode characters you can use GetConsoleMode to detect the handle type, it fails for everything that is not a console handle.

    When doing raw output like this you also have to deal with the BOM if the handle is redirected to a file.

    This blog post is a good starting point for dealing with Unicode in the Windows console...