If I get a handle to stdin from a console app like so:
HANDLE hStdIn = ::GetStdHandle(STD_INPUT_HANDLE);
I can then read data from it:
BYTE buff[32];
DWORD dwcbRead = 0;
BOOL bReadRes = ::ReadFile(hStdIn, buff, SIZEOF(buff), &dwcbRead, NULL);
My question is, how do I know how many bytes are available before I read them?
PS. ReadFile seems to block if there’s no data available to read.
Use
ReadConsoleInputto read raw input events andPeekConsoleInputto examine them without removing from the input queue. There is a bunch of caveats here:Your standard input might be redirected, then you’ll have to determine its type and act accordingly. If it’s a file, it won’t block and you just go ahead and read. If it’s a pipe,
PeekNamedPipeprovides some help.There is no one-to-one correspondence between input events and characters.
If
ENABLE_LINE_MODEis set on the console,ReadFile/ReadConsolewould block if there is no newline yet entered; additionally, line editing facilities are unavailable before you actually callReadConsole, and when you callReadConsole, it will block.I would recommend doing
ReadFileorReadConsole(or trying the latter with fallback to the former) in a separate thread. Your main thread may do something useful and eventually check (or wait for) readyness of the reading thread.