This question already has an answer here:
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
ReadConsoleInput
to read raw input events andPeekConsoleInput
to 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,
PeekNamedPipe
provides some help.There is no one-to-one correspondence between input events and characters.
If
ENABLE_LINE_MODE
is set on the console,ReadFile
/ReadConsole
would 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
ReadFile
orReadConsole
(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.Checking the availability of input on stdin
Yes, you can do that, and yes, it will sit there waiting for your input to fill the buffer. If that's not what you want, then don't use ReadFile.
There are other functions that are meant for reading console I/O, including ones that give you the number of pending "events".
Console IO functions
For console input, you don't know how may characters a user or machine will deliver.
For example, my program asks you to type in a sentence. Which sentence are you thinking of? Which one will you type? How many letters in the sentence?
If you really want to know, I highly recommend a course in reading minds or in the case of the input from a non-human, a course in predicting the future.
For a file, you can check on the size.