linux运行getch吗,怎么样在linux下,实现getch函数功能

本文介绍了一种在Linux环境下实现getch函数的方法,通过使用线程和终端属性设置,可以实现在不按回车的情况下读取键盘输入,并提供了一个具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getch();接受一个任意键的输入,不用按回车就返回。该函数的返回值是所输入字符的ASCII码,且该函数的输入不会自动显示在屏幕上,需要putchar();函数输出显示。getch();函数常用于中途暂停程序方便调试和查看。

有没有办法本人用c语言封装一个在linux下的getch函数?

解决方案

100

看看这个!

[code=c/****************************************

文件名: getkey.h

版本: 1.0

此头文件包含函数:

int getch()

char *getkey()

可用于获取按键信息,具体返回值请自行

测试,编译需加参数 -lpthread

此头文件适用平台:

诺亚舟同步搜学王NP1500/I新春版

made by pengyao1207

注:C++不可用             2013年8月

****************************************/

#include 

#include 

#include 

#include 

#include 

#ifndef _PY_GETKER_H

#define _PY_GETKEY_H

int input;

pthread_t thread[1];

pthread_mutex_t mut;

char c[193]=””;

void *memset();

void *regetch()

{

int n = 0;

n = fgetc( stdin );

input += n;

pthread_exit(NULL);

}

int getch( void )

{

struct termios tm, tm_old;

int fd = STDIN_FILENO,c;

if(tcgetattr(fd, &tm) 

return -1;

tm_old = tm;

cfmakeraw(&tm);

if(tcsetattr(fd, TCSANOW, &tm) 

return -1;

unsigned int k;

int temp;

input = fgetc( stdin );

k = input;

if(tcsetattr(fd,TCSANOW,&tm_old)<0) return -1;

if(k > 32){

c = k;

}

else{

while(1)

{

memset(&thread,0,sizeof(thread));

if((temp = pthread_create(&thread[0],NULL,regetch,NULL))!=0)

printf(“用于获取按键输入的线程创建失败!\n”);

usleep(1000);

pthread_cancel(thread[0]);

pthread_join(thread[0],NULL);

if(k == input) {

c=input;

break;

}

else{

k = input;

c=c+k;

}

}

}

return c;

}

char *getkey(void)

{

int n,i;

char a;

c[0]=”””;

n=getch();

switch(n)

{

case 171:

return “UP”;

case 172:

return “DOWN”;

case 173:

return “RIGHT”;

case 174:

return “LEFT”;

case 27:

return “ESC”;

case 13:

return “OK”;

case 342:

return “AA”;

case 343:

return “BB”;

case 127:

return “DEL”;

case 32:

return “SPACE”;

case 39:

return c;

}

if(n>96)if(n<123)

{

a=”a”;

for(i=97;i

c[0]=a;

return c;

}

if(n>64)if(n<91)

{

a=”A”;

for(i=65;i

c[0]=a;

return c;

}

}

#endif][/code]

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样在linux下,实现getch函数功能!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值