How to get size of data available thru stdin with

2019-08-16 02:04发布

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.

4条回答
够拽才男人
2楼-- · 2019-08-16 02:27

Use ReadConsoleInput to read raw input events and PeekConsoleInput to examine them without removing from the input queue. There is a bunch of caveats here:

  1. 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.

  2. There is no one-to-one correspondence between input events and characters.

  3. 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 call ReadConsole, and when you call ReadConsole, it will block.

I would recommend doing ReadFile or ReadConsole (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.

查看更多
戒情不戒烟
4楼-- · 2019-08-16 02:34

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

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-08-16 02:44

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.

查看更多
登录 后发表回答