开发者

freopen_s on stdout causes problems with GetConsoleScreenBufferInfo on Windows

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 mi开发者_Go百科ght be invalid? Interestingly, printf continues to work as expected and SetConsoleTextAttribute even works with the same handle.


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜