mygetch函数

Linux库中没有提供getch函数,该函数功能是输入一个字符,但并不回显在终端上,这个在Linux下同样可以很简单实现,我们通过更改终端属性则可以做到。当然,这只是一个简单实现,具体可以参考《UNIX高级编程》11章-终端I/O-第10小节-getpass实现。

代码如下:

int mygetch(void)
{
    int ch;
    struct termios oldt, newt;
 
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~ECHO;   /* 关闭回显 */
    newt.c_lflag &= (ECHOE|ICANON);
    newt.c_lflag |= (ECHOE|ICANON);  /* 可以按退格键消除刚刚输入的字符 */
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
 
    return ch;
}

来说两句吧

在评论中,你可以使用以下标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>