使用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 );
}
还有种方法就是捕获键盘事件,不过会复杂点。