Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting keystrokes

Tags:

c

I need to detect a keystroke, without the user pressing enter. What's the most elegant way?

I.e. If the user hits the letter Q, without pressing enter, the program does something.

like image 673
Dominic Bou-Samra Avatar asked Aug 26 '10 00:08

Dominic Bou-Samra


1 Answers

In unix/posix, the standard way of doing this is to put the input into non-canonical mode with tcsetattr:

#include <termios.h>
#include <unistd.h>
    :
struct termios attr;
tcgetattr(0, &attr);
attr.c_lflag &= ~ICANON;
tcsetattr(0, TCSANOW, &attr);

See the termios(3) man page for more details (and probably more information than you wanted to know).

like image 50
Chris Dodd Avatar answered Nov 22 '22 03:11

Chris Dodd