views:

139

answers:

3

How can you view printf output in a win32 application (entering with a WinMain) on visual studio 2010?

+3  A: 

I know that I have done this in the past using the AllocConsole function, but I also recall that it was just a little trickier than I expected.

A quick google search on AllocConsole yeilds what is apparently a Windows Devloper Journal article that seems relevant. From there, the following seems similar to what I recall, vague as it is.

void SetStdOutToNewConsole()
{
  int hConHandle;
  long lStdHandle;
  FILE *fp;

  // allocate a console for this app
  AllocConsole();

  // redirect unbuffered STDOUT to the console
  lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
  hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
  fp = _fdopen( hConHandle, "w" );
  *stdout = *fp;

  setvbuf( stdout, NULL, _IONBF, 0 );
}
torak
+2  A: 

Here is a page that will tell you how to do this, including sample code.

You must create a console window using AllocConsole(), then associate the C standard file handles to the HANDLEs of the new console window.

coffeebean
+1  A: 

You'll need a console window. By far the easiest way to get one is to change a linker option: Project + Properties, Linker, System, SubSystem = Console. Add a main() method:

int main() {
    return _tWinMain(GetModuleHandle(NULL), NULL, GetCommandLine(), SW_SHOW);
}
Hans Passant