3

I expect ReadConsoleW() to return after reading a specific number of bytes. But it doesn't return.

How can I make ReadConsoleW() return as soon as it finished reading the number of bytes specified?

The code I tried is here:

#include <stdio.h>
#include <Windows.h>


int main()
{
    //something is being written to stdin.
    Sleep(2000);
    int b;
    int r;
    //read 3 wide character
    ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &b, 3*sizeof(TCHAR), (LPDWORD)&r, NULL);
    //problem: no returns until enter pressed
    putc(b,stdout);
    while(1)
    {};
}
alk
  • 69,737
  • 10
  • 105
  • 255
kim taeyun
  • 1,837
  • 2
  • 24
  • 49

2 Answers2

2

Use SetConsoleMode to turn off ENABLE_LINE_INPUT flag. No line editing will be available, but it won't wait until the Enter is pressed.

Note that you can't read three WCHARs into an int.

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • 2
    but still it will wait for at least _one_ character in the buffer... i.e. it is still blocking read. – Agnius Vasiliauskas Feb 04 '13 at 07:55
  • 2
    `PeekConsoleInput` is non-blocking, but you have to use `ReadConsoleInput` to consume the input (or check input event types to be sure that `ReadConsoleChars` won't block). (And whenever you want to wait for console events with timeout, just `WaitForSingleObject` on console handle). – Anton Kovalenko Feb 04 '13 at 09:28
-2

Consider also asynchronous I/O in Windows using ReadFile/WriteFile. See MSDN on asynchronous I/O

It is a little more complicated, but you do have what you want.

bash.d
  • 13,029
  • 3
  • 29
  • 42