#include <termio.h>
#include <stdio.h>
int scanKeyboard()
{
int input;
struct termios new_settings;
struct termios stored_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
tcgetattr(0,&stored_settings);
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
in = getchar();
tcsetattr(0,TCSANOW,&stored_settings);
return input;
}
//返回該鍵的ASCII碼值,不需回車
解析:
ICANON
Enable canonical mode. This enables the special characters EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and WERASE, and buffers by lines.
可以看出 ICNAON 標志位啟用了整行緩存。
所以,new_settings.c_lflag &= (~ICANON);這句屏蔽整行緩存。那就只能單個了。
通過tcsetattr函數設置terminal的屬性來控制需不需要回車來結束輸入。
注:通過while循環讀取鍵盤效率很低,參考使用異步事件或者多線程技術。單線程為阻塞式的
【原文】https://blog.csdn.net/alangdangjia/article/details/27697721
在windows下有個鍵盤測試函數,int kbhit(void)。使用該函數需要包含頭文件conio.h。執行時,kbhit測試是否有鍵盤按鍵按下,若有則返回非零值,否則返回零。
在Unix/Linux下,並沒有提供這個函數。在linux下開發控制台程序時,有時會遇到檢測鍵盤是否有被按下的情況,這時就需要自己編寫 kbhit() 實現的程序了。
#include <stdio.h>
#include <termios.h>
static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);
void init_keyboard()
{
tcgetattr(0,&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag |= ICANON;
new_settings.c_lflag |= ECHO;
new_settings.c_lflag |= ISIG;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
void close_keyboard()
{
tcsetattr(0, TCSANOW, &initial_settings);
}
int kbhit()
{
unsigned char ch;
int nread;
if (peek_character != -1) return 1;
new_settings.c_cc[VMIN]=0;
tcsetattr(0, TCSANOW, &new_settings);
nread = read(0,&ch,1);
new_settings.c_cc[VMIN]=1;
tcsetattr(0, TCSANOW, &new_settings);
if(nread == 1)
{
peek_character = ch;
return 1;
}
return 0;
}
int readch()
{
char ch;
if(peek_character != -1)
{
ch = peek_character;
peek_character = -1;
return ch;
}
read(0,&ch,1);
return ch;
}
int main()
{
init_keyboard();
while(1)
{
kbhit();
printf("\n%d\n", readch());
}
close_keyboard();
return 0;
}
linux termios 結構:
https://blog.csdn.net/querdaizhi/article/details/7436722
