如何在Linux中实现C的getch()函数? [英] How to implement getch() function of C in Linux?

查看:28
本文介绍了如何在Linux中实现C的getch()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TurboC++ 中,我可以使用 conio.h 中的 getch() 函数.但是在 Linux 中,gcc 不提供 conio.h.如何获得 getch() 的功能?

In TurboC++, I can use the getch() function from conio.h. But in Linux, gcc doesn't provide conio.h. How can I get the functionality of getch()?

推荐答案

试试这个 conio.h 文件:

#include <termios.h>
#include <unistd.h>
#include <stdio.h>

/* reads from keypress, doesn't echo */
int getch(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

/* reads from keypress, echoes */
int getche(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

您也可以使用 gcc 中的 ncurses 库来实现一些类似于 conio 的功能.h.

You can also use the ncurses library in gcc for some functions similar to conio.h.

这篇关于如何在Linux中实现C的getch()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆