在Unix/Linux下,并没有提供int kbhit(void)这个
函数。在linux下开发控制台
程序时,需要自己编写kbhit()实现的程序了。下面是kbhit在Unix/Linux下的一个实现。用到了一种终端 *** 作库termios。下面是头文件kbhit.h:QUOTE:#ifndef KBHITh#define KBHIThvoid init_keyboard(void)void close_keyboard(void)int kbhit(void)int readch(void)#endif下面式
源程序kbhit.c:QUOTE:#include "kbhit.h"#include <stdio.h>#include <termios.h>static struct termios initial_settings, new_settingsstatic int peek_character = -1void init_keyboard(){tcgetattr(0,&initial_settings)new_settings = initial_settingsnew_settings.c_lflag &= ~ICANONnew_settings.c_lflag &= ~ECHOnew_settings.c_lflag &= ~ISIGnew_settings.c_cc[VMIN] = 1new_settings.c_cc[VTIME] = 0tcsetattr(0, TCSANOW, &new_settings)}void close_keyboard(){tcsetattr(0, TCSANOW, &initial_settings)}int kbhit(){unsigned char chint nreadif (peek_character != -1) return 1new_settings.c_cc[VMIN]=0tcsetattr(0, TCSANOW, &new_settings)nread = read(0,&ch,1)new_settings.c_cc[VMIN]=1tcsetattr(0, TCSANOW, &new_settings)if(nread == 1) {peek_character = chreturn 1}return 0}int readch(){char chif(peek_character != -1) {ch = peek_characterpeek_character = -1return ch}read(0,&ch,1)return ch}
自己写函数
#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
}
评论列表(0条)