Discussion:
GetConsoleMode fails when input piped
(too old to reply)
Ritchie
2003-08-05 12:12:58 UTC
Permalink
Hi all,
I've been experimenting with reading/writing to StdIn/Stdout using
ReadFile and WriteFile and noticed that GetConsoleMode() always fails
if anything is piped into the application, GetLastError returns 6,
which means "The handle in invalid". Surely, if the handle was invalid,
then GetStdHandle() would have failed. Any ideas why this happens?

================= screen dump ==================
D:\data\msdev\test\Debug> dir | test
Error 6: GetConsoleMode failed

D:\data\msdev\test\Debug> test < myfile.txt
Error 6: GetConsoleMode failed

D:\data\msdev\test\Debug> test
Error 0: No errors
================= screen dump ==================

And here's a trimmed version of the code:-

#include <windows.h>
#include <stdio.h>

int main(void)
{
HANDLE hStdIn;
DWORD dwStdInMode;

hStdIn = GetStdHandle(STD_INPUT_HANDLE);

if(hStdIn == INVALID_HANDLE_VALUE)
return printf("Error %d: GetStdHandle failed\n", GetLastError());

if(!GetConsoleMode(hStdIn, &dwStdInMode))
return printf("Error %d: GetConsoleMode failed\n", GetLastError());

return printf("Error %d: No errors\n", GetLastError());
}

--
Ritchie
Tim Robinson
2003-08-05 18:13:26 UTC
Permalink
The handle is not a valid console handle, but that's not to say it isn't a
valid file handle. I would handle errors from GetConsoleMode gracefully
(i.e. if it fails, don't use it), or examine the value returned from
GetFileType.
--
Tim Robinson (MVP, Windows SDK)
http://www.themobius.co.uk/
Post by Ritchie
Hi all,
I've been experimenting with reading/writing to StdIn/Stdout using
ReadFile and WriteFile and noticed that GetConsoleMode() always fails
if anything is piped into the application, GetLastError returns 6,
which means "The handle in invalid". Surely, if the handle was invalid,
then GetStdHandle() would have failed. Any ideas why this happens?
================= screen dump ==================
D:\data\msdev\test\Debug> dir | test
Error 6: GetConsoleMode failed
D:\data\msdev\test\Debug> test < myfile.txt
Error 6: GetConsoleMode failed
D:\data\msdev\test\Debug> test
Error 0: No errors
================= screen dump ==================
And here's a trimmed version of the code:-
#include <windows.h>
#include <stdio.h>
int main(void)
{
HANDLE hStdIn;
DWORD dwStdInMode;
hStdIn = GetStdHandle(STD_INPUT_HANDLE);
if(hStdIn == INVALID_HANDLE_VALUE)
return printf("Error %d: GetStdHandle failed\n", GetLastError());
if(!GetConsoleMode(hStdIn, &dwStdInMode))
return printf("Error %d: GetConsoleMode failed\n", GetLastError());
return printf("Error %d: No errors\n", GetLastError());
}
--
Ritchie
Loading...