如何获得大小的数据可用通过stdin与C ++ [英] How to get size of data available thru stdin with C++

查看:397
本文介绍了如何获得大小的数据可用通过stdin与C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从控制台应用程序中得到 stdin 的句柄:

If I get a handle to stdin from a console app like so:

HANDLE hStdIn = ::GetStdHandle(STD_INPUT_HANDLE);

我可以从中读取数据:

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 似乎阻止如果没有可供阅读的数据。

PS. ReadFile seems to block if there's no data available to read.

推荐答案

使用 ReadConsoleInput 来读取原始输入事件,使用 PeekConsoleInput 来检查它们,而不从输入队列中删除。这里有一些注意事项:

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. 您的标准输入可能会重定向,那么您必须确定其类型,相应地行动。如果它是一个文件,它不会阻止,你只是继续阅读。如果是管道, PeekNamedPipe 提供了一些帮助。

没有一一对应

如果 ENABLE_LINE_MODE 在控制台上设置, ReadFile / 如果没有输入换行符,则ReadConsole 此外,在您实际调用 ReadConsole 之前,以及当您调用 ReadConsole

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.

我建议您使用 ReadFile ReadConsole (或尝试后者与后者)。你的主线程可能会做一些有用的事情,最终检查(或等待)阅读线程的准备。

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.

这篇关于如何获得大小的数据可用通过stdin与C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆