Skip to content

Instantly share code, notes, and snippets.

@Xsoda
Created July 16, 2012 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Xsoda/3120099 to your computer and use it in GitHub Desktop.
Save Xsoda/3120099 to your computer and use it in GitHub Desktop.
using stdout in GUI programs
/**
* The following function shows one way that a GUI application can redirect the stdout
* stream to a new console window. After the following function has been called, the
* GUI program can use C runtime functions like printf to display information on the
* console window. This can be useful during debugging.
*/
// Version 1:
void RedirectStdOut(void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
// Create a new console window.
if (!AllocConsole()) return;
// Set the screen buffer to be larger than normal (this is optional).
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
csbi.dwSize.Y = 1000; // any useful number of lines...
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csbi.dwSize);
}
// Redirect "stdout" to the console window.
fclose(stdout);
setbuf(stdout, NULL);
*stdout = *_fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), "w");
}
// Version 2:
void RedirectStdOut(void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
// Create a new console window.
if (!AllocConsole()) return;
// Set the screen buffer to be larger than normal (this is optional).
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
{
csbi.dwSize.Y = 1000; // any useful number of lines...
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), csbi.dwSize);
}
// Redirect "stdin" to the console window.
if (!freopen("CONIN$", "w", stdin)) return;
// Redirect "stderr" to the console window.
if (!freopen("CONOUT$", "w", stderr)) return;
// Redirect "stdout" to the console window.
if (!freopen("CONOUT$", "w", stdout)) return;
// Turn off buffering for "stdout" ("stderr" is unbuffered by default).
setbuf(stdout, NULL);
}
@niclet
Copy link

niclet commented Apr 11, 2017

Hi,
It seems that first version doesn't work with VS2015, at least "*stdout = " line has no effect.
FILE struct, and stdin/stdout/stderr have been redefined in VS2015
2nd version still works, thanks ;)
Regards.

@PaulBoersma
Copy link

The second version is incorrect, because it obliterates the distinction between stdout and stderr. For instance, you will not be able to have stdout redirected to a file and at the same time have stderr writing to the console window. The version with _open_osfhandle does maintain the distinction between stdout and stderr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment