views:

170

answers:

1

To temporarily redirect stdout to a file, I'm doing:

printf("Before");
freopen_s(&stream, "test.txt", "w", stdout);
printf("During");
freopen_s(&stream, "CONOUT$", "w", stdout);
printf("After");

That works, however doing:

CONSOLE_SCREEN_BUFFER_INFO sbi = {0};
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbi);

No longer seems to work. It is returning false and GetLastError() is returning 6 which translates into the message "The handle is invalid." with FormatMessage.

Any advice on why the handle might be invalid? Interestingly, printf continues to work as expected and SetConsoleTextAttribute even works with the same handle.

+1  A: 

I discovered the following here:

hConsoleOutput [in]

A handle to the console screen buffer. The handle must have the GENERIC_READ access right. For more information, see Console Buffer Security and Access Rights.

Thus, I would expect that adding read access to the reopen would restore the expected functionality, for example:

printf("Before");
freopen_s(&stream, "test.txt", "w", stdout);
printf("During");
freopen_s(&stream, "CONOUT$", "w+", stdout);
printf("After");
Charles Sigismund
That fixed my problem. Thanks!
Sydius