原文地址:http://www.sbin.org/doc/unix-faq/programmer/faq_4.html
How can I read single characters from the terminal? My program is always waiting for the user to pressRETURN.
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 usegetc()
to grab the key pressed immediately by the user. We use tcgetattr()
and tcsetattr()
both of which are defined by POSIX to manipulate thetermios
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; }