設定終端屬性,不用回車獲取終端輸入字元
阿新 • • 發佈:2019-02-14
使用termios(3)及相關函式,適當的設定終端屬性,不用回車即可獲取終端輸入的字元。
#include <stdio.h> #include <termios.h> int main() { int c; struct termios oldSet,newSet; tcgetattr(fileno(stdin),&oldSet); newSet = oldSet; newSet.c_lflag &= ~ECHO; newSet.c_lflag &= ~ICANON; //VMIN等待最小的字元數 newSet.c_cc[VMIN] = 1; //等待的最小時間 newSet.c_cc[VTIME] = 0; if( tcsetattr(fileno(stdin),TCSAFLUSH,&newSet)!= 0 ) { fprintf( stderr,"Could not set attrbutes of terminal!\n" ); } else { while( (c = getchar()) != 'q' ) { printf("you intput the char:%c \n",c); } } tcsetattr( fileno(stdin),TCSANOW,&oldSet ); }
還有種方法就是捕獲鍵盤事件,不過會複雜點。