linux中实现getch函数

思想是把终端设置为非缓存

 

  1. #include <stdio.h>   
  2. #include <termios.h>   
  3. #include <unistd.h>   
  4. #include <assert.h>   
  5. #include <string.h>   
  6.   
  7. int getch(void);   
  8.   
  9. int main(void)   
  10. {   
  11.         char ch;   
  12.         printf("Input a char:");   
  13.         fflush(stdin);   
  14.         ch = getch();   
  15.         printf("\nYou input character is: %c\n", ch);   
  16.         return 0;   
  17. }   
  18.   
  19. int getch(void)   
  20. {   
  21.         int c=0;   
  22.         struct termios org_opts, new_opts;   
  23.         int res=0;   
  24.         //-----  store old settings -----------   
  25.         res=tcgetattr(STDIN_FILENO, &org_opts);   
  26.         assert(res==0);   
  27.         //---- set new terminal parms --------   
  28.         memcpy(&new_opts, &org_opts, sizeof(new_opts));   
  29.         new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);   
  30.         tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);   
  31.         c=getchar();   
  32.             //------  restore old settings ---------   
  33.         res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);assert(res==0);   
  34.         return c;   
  35. }  

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值