gpt4 book ai didi

c - 如何在Linux中实现C的getch()函数?

转载 作者:太空狗 更新时间:2023-10-29 16:31:33 27 4
gpt4 key购买 nike

在 TurboC++ 中,我可以使用 conio.h 中的 getch() 函数。但在 Linux 中,gcc 不提供 conio.h。如何获得 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;
}

您还可以使用 ncurses gcc 中的一些函数类似于 conio.h 的库。

关于c - 如何在Linux中实现C的getch()函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3276546/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com