Created
July 16, 2012 02:46
-
-
Save Xsoda/3120099 to your computer and use it in GitHub Desktop.
using stdout in GUI programs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
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
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.