Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4190920
  • 博文数量: 776
  • 博客积分: 13014
  • 博客等级: 上将
  • 技术积分: 10391
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-22 17:00
文章分类

全部博文(776)

文章存档

2015年(55)

2014年(43)

2013年(147)

2012年(20)

2011年(82)

2010年(429)

分类: LINUX

2010-02-22 20:27:06

//********linux下的getch函数与kbhit函数********
 
 // 在linux下需要修改terminal的属性
#include
#include
#include
#include
#include
#include
#include
#include
 
#undef TERMIOSECHO
#define TERMIOSFLUSH
 
/*
 * kbhit() -- a keyboard lookahead monitor
 *
 * returns the number of characters available to read
 */
static int kbhit ( void )
{
    struct timeval tv;
    struct termios old_termios, new_termios;
    int            error;
    int            count = 0;
    tcgetattr( 0, &old_termios );
    new_termios              = old_termios;
    /*
     * raw mode
     */
    new_termios.c_lflag     &= ~ICANON;
    /*
     * disable echoing the char as it is typed
     */
    new_termios.c_lflag     &= ~ECHO;
    /*
     * minimum chars to wait for
     */
    new_termios.c_cc[VMIN]   = 1;
    /*
     * minimum wait time, 1 * 0.10s
     */
    new_termios.c_cc[VTIME]  = 1;
    error                    = tcsetattr( 0, TCSANOW, &new_termios );
    tv.tv_sec                = 0;
    tv.tv_usec               = 100;
    /*
     * insert a minimal delay
     */
    select( 1, NULL, NULL, NULL, &tv );
    error                   += ioctl( 0, FIONREAD, &count );
    error                   += tcsetattr( 0, TCSANOW, &old_termios );
    return( error == 0 ? count : -1 );
}  /* end of kbhit */
/*------------------------------------------------*/
int getch( void )
{
      int c = 0;
      struct termios org_opts, new_opts;
      int res = 0;
          //-----  store old settings -----------
      res = tcgetattr( STDIN_FILENO, &org_opts );
      assert( res == 0 );
          //---- set new terminal parms --------
      memcpy( &new_opts, &org_opts, sizeof(new_opts) );
      new_opts.c_lflag &= ~( ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL );
      tcsetattr( STDIN_FILENO, TCSANOW, &new_opts );
      c = getchar();
          //------  restore old settings ---------
      res = tcsetattr( STDIN_FILENO, TCSANOW, &org_opts );
      assert( res == 0 );
      return( c );
}
阅读(1857) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~