Simple Debugging with AllocConsole

If you are familiar with the AllocConsole() Windows API then you have more than likely had a need to create a console for a window (as opposed to console) application. And since you opted to do it programmatically, I can assume that you only want the console open some of the time – and probably for debugging purposes.

Annoyingly, if you open a console from within a windows application, the only way to write to it is by calling WriteFile() and read using ReadFile() - passing them both a handle acquired via GetStdHandle(). This really screws up my debugging because I use printf() for all of my verbose logging. Printf allows me to cleanly format my output with line breaks, tabs and numeric formatting – WriteFile() doesn't take any of these formatters, thereby forcing me to fall back to sprintf() to build formatted strings and then pass them to WriteFile().

Fortunately - hope is not lost! We can get the actual OS file handle of the STD-I/O handles, open them as file descriptors and then redirect the I/O pointers - thus allowing you to use the same ol' Win32API you've become accustomed to.

In short, with these two functions, you can Alloc a Console, redirect the I/O and continue using printf, gets, ect.

void DebugRedirectOutput(void)
{
 	int hCrt, i;
	FILE *hf;
	hCrt = _open_osfhandle((long) GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
	hf = _fdopen(hCrt, "r" );
	*stdin = *hf;
	i = setvbuf(stdin, NULL, _IONBF, 0);
}

Redirect stdin to the newly allocated console to that functions such as gets() can read from it:

void DebugRedirectInput(void)
{
	int hCrt, i;
	FILE *hf;
	hCrt = _open_osfhandle((long) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
	hf = _fdopen( hCrt, "w" );
	*stdout = *hf;
	i = setvbuf(stdout, NULL, _IONBF, 0);
}

Example usage and required include files:

#include <windows.h>
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	if(AllocConsole())
	{
		DebugRedirectOutput();
		DebugRedirectInput();

		printf("Hello World!");
	}
	return 0;
}