>I'm a bit of a newbie in this, so this could be a stupid
>question. I'm writing a program (in C) that needs to
>check to see if the user typed a character to the screen,
>without waiting for that character if it isn't there.
>So, while I'm doing a bunch of stuff in a while(1) type
>of loop, the user could type 'q' to the screen, and at
>a certain spot in the loop, the program would check to
>see if the user typed 'q'. If the user didn't type anything,
>I would want it to continue on as if nothing happened.
>Is this possible? I was told to mess around with the termios
>settings, but I haven't figured it out yet.
>Thanks!
>Sent via Deja.com http://www.deja.com/
>Before you buy.
From the FAQ:
3.2 How can I read single characters from the terminal?
=======================================================
How can I read single characters from the terminal? My program is
always waiting for the user to press `<RETURN>'.
Terminals are usually in canonical mode, where input is read in lines
after it is edited. You may set this into non-canonical mode, where you
set how many characters should be read before
input is given to your program. You also may set the timer in
non-canonical mode terminals to 0, this timer flushs your buffer at set
intervals. By doing this, you can use `getc()' to grab the
key pressed immediately by the user. We use `tcgetattr()' and
`tcsetattr()' both of which are defined by POSIX to manipulate the
`termios' structure.
#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <string.h>
static struct termios stored_settings;
void set_keypress(void)
{
struct termios new_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
/* Disable canonical mode, and set buffer size to 1 byte */
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
return;
}
void reset_keypress(void)
{
tcsetattr(0,TCSANOW,&stored_settings);
return;
}
3.3 How can I check and see if a key was pressed?
=================================================
How can I check and see if a key was pressed? On DOS I use the
`kbhit()' function, but there doesn't seem to be an equivalent?
If you set the terminal to single-character mode (see previous answer),
then (on most systems) you can use `select()' or `poll()' to test for
readability.
--