Search code examples
ciononblocking

Non-Blocking i/o in c? (windows)


I'm trying to get a non-blocking I/O on a Windows terminal application (windows only, sorry!).

What if I want to have a short input time in wich the user can press a button, but if he doesn't the input stops and the program continues?

For example:

A timer that counts from 1 to whatever that stops when the user presses a certain key: I should have a while loop, but if I do a getch or a getchar function it will stop the program, right?

I know I could use kbhit(); , but for the "program" I'm trying to make I need to know the input, not just IF THERE IS input! Are there any simple functions that would allow me to read like the last key in the keyboard buffer?


Solution

  • From the documentation for _kbhit():

    The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.

    So, in your loop:

    while (true) {
        // ...
        if (_kbhit()) {
            char c = _getch();
            // act on character c in whatever way you want
        }
    }
    

    So, you can still use _getch(), but limit its use to only after _kbhit() says there is something waiting. That way it won't block.