Last active
August 15, 2021 09:39
-
-
Save genbtc/45aae86e4a4280ba8ca9f8e77a072e29 to your computer and use it in GitHub Desktop.
Console buffer handle
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
void RedirectIOToConsole() { | |
//Create a console for this application | |
AllocConsole(); | |
// Get STDOUT handle | |
HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); | |
int SystemOutput = _open_osfhandle(intptr_t(ConsoleOutput), _O_TEXT); | |
FILE *COutputHandle = _fdopen(SystemOutput, "w"); | |
// Get STDERR handle | |
HANDLE ConsoleError = GetStdHandle(STD_ERROR_HANDLE); | |
int SystemError = _open_osfhandle(intptr_t(ConsoleError), _O_TEXT); | |
FILE *CErrorHandle = _fdopen(SystemError, "w"); | |
// Get STDIN handle | |
HANDLE ConsoleInput = GetStdHandle(STD_INPUT_HANDLE); | |
int SystemInput = _open_osfhandle(intptr_t(ConsoleInput), _O_TEXT); | |
FILE *CInputHandle = _fdopen(SystemInput, "r"); | |
//make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well | |
std::ios::sync_with_stdio(true); | |
// Redirect the CRT standard input, output, and error handles to the console | |
freopen_s(&CInputHandle, "CONIN$", "r", stdin); | |
freopen_s(&COutputHandle, "CONOUT$", "w", stdout); | |
freopen_s(&CErrorHandle, "CONOUT$", "w", stderr); | |
//Clear the error state for each of the C++ standard stream objects. We need to do this, as | |
//attempts to access the standard streams before they refer to a valid target will cause the | |
//iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems | |
//to always occur during startup regardless of whether anything has been read from or written to | |
//the console or not. | |
std::wcout.clear(); | |
std::cout.clear(); | |
std::wcerr.clear(); | |
std::cerr.clear(); | |
std::wcin.clear(); | |
std::cin.clear(); | |
// test CrtDbg output | |
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); | |
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); | |
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); | |
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); | |
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); | |
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); | |
_RPT0(_CRT_WARN, "This is testing _CRT_WARN output\n"); | |
_RPT0(_CRT_ERROR, "This is testing _CRT_ERROR output\n"); | |
_ASSERT(0 && "testing _ASSERT"); | |
_ASSERTE(0 && "testing _ASSERTE"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment