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

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

问题描述

在涡轮C ++中,我们可以使用的getch()函数提供CONIO.H。

In turbo c++, we can use getch() function available in conio.h.

但是在linux,gcc编译器不提供CONIO.H头文件,那么如何获得的getch()函数?功能

But in linux, gcc compiler doesn't provide conio.h header file, then how to get functionality of getch() function?

推荐答案

这code添加到命名为CONIO.H一个新的文件,包括该文件当过你需要的getch或getche:

Add this code to a new file named as conio.h and include this file when ever you need getch or getche:

#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;
}

也可以使用ncurses的库GCC为CONIO.H其他一些类似的功能。

or you can use "ncurses" library in gcc for some other similar functions of "conio.h".

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

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