① 没有直接的对应,需要自己实现。
② 可以写c函数、汇编、或用第3方跨平台的函数库(比如ncurses)。下面是linux下c函数实现:
#include <stdio.h>#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
void changemode(int)
int kbhit(void)
int main(void)
{
int ch
changemode(1) /* 注意,打开mode */
while ( !kbhit() )
{
putchar('.')
}
ch = getchar()
printf("\nGot %c\n", ch)
changemode(0) /* 注意,关闭mode */
return 0
}
void changemode(int dir)
{
static struct termios oldt, newt
if ( dir == 1 )
{
tcgetattr( STDIN_FILENO, &oldt)
newt = oldt
newt.c_lflag &= ~( ICANON | ECHO )
tcsetattr( STDIN_FILENO, TCSANOW, &newt)
}
else
tcsetattr( STDIN_FILENO, TCSANOW, &oldt)
}
int kbhit (void)
{
struct timeval tv
fd_set rdfs
tv.tv_sec = 0
tv.tv_usec = 0
FD_ZERO(&rdfs)
FD_SET (STDIN_FILENO, &rdfs)
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv)
return FD_ISSET(STDIN_FILENO, &rdfs)
}
---- 上述代码来自互联网。
在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}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)