linux记录键盘

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #include<termios.h>
 5 #include<term.h>
 6 #include<curses.h>
 7 #include<unistd.h>
 8 static struct termios initial_settings,new_settings;
 9 static int peek_character=-1;
10 void init_keyboard();
11 void close_keyboard();
12 int check_keyboard();
13 int readch();
14 int main()
15 {
16     int ch=0;
17     init_keyboard();
18     while(ch!='q')
19     {
20         printf("looping\n");
21         sleep(1);    
22         if(check_keyboard())
23         {
24         ch=readch();
25     ///    scanf("%c",&ch);
26         printf("You hit %c\n",ch);
27         }
28     }
29     close_keyboard();
30     exit(0);
31 }
32 
33 int readch()
34 {
35     char ch;
36     if(peek_character!=-1)
37     {
38         ch=peek_character;
39         peek_character=-1;
40         return ch;
41     }
42     read(0,&ch,1);
43     return ch;
44 } 
45 
46 void init_keyboard()
47 {
48     tcgetattr(0,&initial_settings);
49     new_settings=initial_settings;
50     new_settings.c_lflag &=~ICANON;
51     new_settings.c_lflag &=~ECHO;
52     new_settings.c_lflag &=~ISIG;
53     new_settings.c_cc[VTIME]=0;
54     new_settings.c_cc[VMIN]=1;
55     tcsetattr(0,TCSANOW,&new_settings);
56 }
57 
58 void close_keyboard()
59 {
60     tcsetattr(0,TCSANOW,&initial_settings);
61 }
62 
63 int check_keyboard()
64 {
65     char ch;
66     int nread;
67     if(peek_character!=-1)
68     {
69         return 1;
70     }
71     new_settings.c_cc[VMIN]=0;
72     tcsetattr(0,TCSANOW,&new_settings);
73     nread=read(0,&ch,1);
74     new_settings.c_cc[VMIN]=1;
75     tcsetattr(0,TCSANOW,&new_settings);
76     if(nread==1)
77     {
78     peek_character=ch;
79     return 1;
80     }
81     return 0;
82 }

如图所示,按q退出

转载于:https://www.cnblogs.com/newworldcom/p/4101566.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值