linux下实现getch()函数的功能

#include <termio.h>

int getch(void)
{
     struct termios tm, tm_old;
     int fd = 0, ch;
 
     if (tcgetattr(fd, &tm) < 0) {//保存现在的终端设置
          return -1;
     }
 
     tm_old = tm;
     cfmakeraw(&tm);//更改终端设置为原始模式,该模式下所有的输入数据以字节为单位被处理
     if (tcsetattr(fd, TCSANOW, &tm) < 0) {//设置上更改之后的设置
          return -1;
     }
 
     ch = getchar();
     if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {//更改设置为最初的样子
          return -1;
     }
    
     return ch;
}
总体的思路就是设置终端的属性
设置为原始模式,这种模式下输入就是无缓冲的,
设置过去,输入完之后然后再更改回来
主要就是两个函数
tcgetattr()和tcsetattr()
这个可以百度获取详细信息
posted @ 2014-06-13 11:38  老高是我  阅读(771)  评论(0编辑  收藏  举报