views:

247

answers:

4

Hi,

I'm trying to make a little console application that is able to deal with keystrokes as events. What I need is mostly the ability to get the keystrokes and be able to do something with them without dealing with the typical stdin reading functions.

I tried to check the code of programs like mplayer, which implement this (for stopping the play, for example), but I can't get to the core of this with such a big code base.

Thanks

+2  A: 

At the core of said applications you'll find select(2). Just use it against stdin to find out when you can read input from it.

Ignacio Vazquez-Abrams
By default, you can only read from stdin once a full line was received, so that's when select will return too. You need to mess with disabling line buffering too.
Nicolás
+2  A: 

See if you have access to the getch() function. With this function you can retrieve a single keystroke, even (CTRL+(char)) keystrokes. After you have this data I suppose it's up to you to just create a handler for this event. So what you could do is implement a table of index/function ptr pairs, using the keystroke as an index, and assigning each index a function pointer to handle that event. Hope this helps.

Brandon
+4  A: 

You could use the ncurses family of functions 'getch' as shown in the link, here's another link that will be of help to you, by the way, it should be pointed out, ncurses is platform portable so you should be pretty ok with it if you decide to re-target to another platform which is a big plus...

tommieb75
+2  A: 

To change stdin to not buffer until enter is hit, you can mess around with the terminal i/o settings like so..

struct termios oldopts;
struct termios newopts;

tcgetattr(fileno(stdin), &oldopts);
newopts = oldopts;
newopts.c_lflag &= (~ICANON & ~ECHO);
tcsetattr(fileno(stdin), TCSANOW, &newopts);

The termios structure and the tcgetattr() and tcsetattr() prototypes are in the termios.h file.
Then you can use select() to check whether a char is ready to be read.

JustJeff