Linux and many other operating systems buffer all input before making it available to a program. This is done so that the OS can control the editing of input, thus freeing the programmer from this responsibility. The input normally becomes accessible when the user types the ENTER key.
However, at times it is desirable to get and use individual keystrokes as they are typed. For example, this can occur when the user is presented with a menu.
To make this possible, you need to turn off the automatic buffering. The program below does this. You can trace through it with gdb to examine the codes as they are passed from the keyboard.
/* singlekey.c
DFStermole
12 October 98
Purpose: Get single characters from keyboard
*/
#include <stdio.h> /* standard I/O header file */
#include <stdlib.h>
#include <termios.h>
#include <string.h>
/* function prototypes */
void set_keypress(void);
void reset_keypress(void);
static struct termios stored;
void main()
{
int i; /* count */
char str[80]; /* storage for input string */
int c; /* temporary storage for input character */
int cc;
set_keypress();
i = 0;
while( ( (c = getc(stdin)) != EOF) && (c != (int)'\n') )
{
printf("%c\n", (char)c); /* FOR TEST PURPOSES ONLY!! */
str[i++] = (char)c;
}
str[i] = '\0';
reset_keypress();
printf("%s\n", str);
}
/* The following code was found in the
Unix Programmer FAQ 3.2
on the RTFM site
at the Massachusetts Institute of Technology.
*/
void set_keypress(void)
{
struct termios new;
tcgetattr(0,&stored);
memcpy(&new,&stored,sizeof(struct termios));
/* Disable canonical mode, and set buffer size to 1 byte */
new.c_lflag &= (~ICANON);
new.c_cc[VTIME] = 0;
new.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new);
return;
}
void reset_keypress(void)
{
tcsetattr(0,TCSANOW,&stored);
return;
}