I'm trying to redirect traces on an output console on Windows Visual 2012, Linker/Subsystem = Windows (/SUBSYSTEM:WINDOWS), using a classical RedirectIOToConsole function.
Performing std::endl before AllocConsole seems to causes problems to display traces.
Below is my test:
#include <windows.h>
#include <stdio.h>
#include <iostream>
void RedirectIOToConsole()
{
FILE *conin, *conout;
AllocConsole();
freopen_s(&conin, "conin$", "r", stdin);
freopen_s(&conout, "conout$", "w", stdout);
freopen_s(&conout, "conout$", "w", stderr);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// std::cout << "My Trace 1"; // Uncomment this line for Test 1
// std::cout << "My Trace 1" << std::endl; // Uncomment this line for Test 2
RedirectIOToConsole();
printf( "redirected console\n");
std::cout << "My Trace 2" << std::endl;
ch = getchar();
return 0;
}
redirected console
My Trace 2 -> OK
redirected console
My Trace 2 -> OK
redirected console -> NOK
Before you call RedirectIOToConsole()
there is nothing for cout
to output onto. Since cout
is buffered, the output is stored in a buffer until a flush
is performed. endl
contains a flush
.
When you try to flush the output with no console available, the cout
stream sets the badbit
in the iostate
.
When you then do the next step of cout << "My Trace 2" << endl;
the output is not proceeding because before actually writing the data to the output file (stdout), cout
checks the iostate
and says "Oh, this is not good, we have badbit
set" and bails out without trying to write.
You could, in theory, fix this by calling cout.clear();
, but I would suggest that it's a better plan to not call cout
before you have allocated a console - it serves no purpose to output things before you have something to output to.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.