Skip to content

Instantly share code, notes, and snippets.

@Shauren
Created February 22, 2016 17:09
Show Gist options
  • Save Shauren/5fb2b7662c7a1a44e837 to your computer and use it in GitHub Desktop.
Save Shauren/5fb2b7662c7a1a44e837 to your computer and use it in GitHub Desktop.
open console & redirect there
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <cstdio>
#include <fcntl.h>
#include <io.h>
#include <streambuf>
void RedirectHandle(DWORD handle, FILE* file, char const* mode)
{
long lStdHandle = (long)GetStdHandle(handle);
int hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
*file = *_fdopen(hConHandle, mode);
setvbuf(file, NULL, _IONBF, 0);
}
void CreateConsole()
{
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
CONSOLE_SCREEN_BUFFER_INFO coninfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = 300;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect unbuffered STDOUT to the console
RedirectHandle(STD_OUTPUT_HANDLE, stdout, "w");
RedirectHandle(STD_INPUT_HANDLE, stdin, "r");
RedirectHandle(STD_ERROR_HANDLE, stderr, "w");
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
std::ios_base::sync_with_stdio();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment