0

stdin如果我像这样从控制台应用程序获得句柄:

HANDLE hStdIn = ::GetStdHandle(STD_INPUT_HANDLE);

然后我可以从中读取数据:

BYTE buff[32];
DWORD dwcbRead = 0;
BOOL bReadRes = ::ReadFile(hStdIn, buff, SIZEOF(buff), &dwcbRead, NULL);

我的问题是,在读取它们之前我怎么知道有多少字节可用?

PS。ReadFile如果没有可读取的数据,似乎会阻塞。

4

4 回答 4

1

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.

于 2013-02-13T20:44:12.583 回答
1

检查 stdin 上输入的可用性

于 2013-02-13T20:36:54.893 回答
1

对于控制台输入,您不知道用户或机器将提供多少字符。
例如,我的程序要求你输入一个句子。你在想哪句话?你会打哪一个?句子中有多少个字母?

如果你真的想知道,我强烈推荐一门阅读思想的课程,或者在非人类输入的情况下,一门预测未来的课程。

对于文件,您可以检查大小。

于 2013-02-13T20:37:13.010 回答
0

是的,你可以这样做,是的,它会坐在那里等待你的输入来填充缓冲区。如果这不是你想要的,那么不要使用 ReadFile。

还有其他用于读取控制台 I/O 的功能,包括为您提供待处理“事件”数量的功能。

控制台 IO 功能

于 2013-02-13T20:40:48.277 回答