Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

CSC112 Spring 2016 Examples

2370 views
1
#include <stdio.h>
2
#include <unistd.h>
3
#include <termios.h>
4
#include <sys/ioctl.h>
5
#include <stdlib.h>
6
#include <sys/poll.h>
7
#include <stropts.h>
8
9
10
int getkey()
11
{
12
char k;
13
14
read(STDIN_FILENO, &k, 1);
15
16
return k;
17
}
18
19
20
int hasInput()
21
{
22
struct pollfd fds;
23
int pres;
24
25
fds.fd=STDIN_FILENO;
26
fds.events=POLLIN;
27
pres = poll(&fds, 1, 0);
28
29
return pres==1;
30
}
31
32
33
34
void setMode(int _echo, int _canonical, int _signal, int _special)
35
{
36
struct termios t;
37
38
//get the current termios
39
if(tcgetattr(STDIN_FILENO, &t) == -1) {
40
return; //TODO Exception Handling
41
}
42
43
44
//echo handling
45
if(_echo) {
46
//set the ECHO flag
47
t.c_lflag |= ECHO;
48
} else {
49
//clear the ECHO flag
50
t.c_lflag &= ~ECHO;
51
}
52
53
//canonical handling
54
if(_canonical) {
55
t.c_lflag |= ICANON;
56
t.c_iflag |= ICRNL;
57
} else {
58
t.c_lflag &= ~ICANON;
59
t.c_iflag &= ~ICRNL;
60
}
61
62
//singal handling
63
if(_signal) {
64
t.c_lflag |= ISIG | IEXTEN;
65
} else {
66
t.c_lflag &= ~(ISIG | IEXTEN);
67
}
68
69
70
//special processing handling
71
if(_special) {
72
t.c_iflag |= BRKINT | INPCK | IGNBRK | ISTRIP | IGNCR | IXON | INLCR | PARMRK;
73
t.c_oflag |= OPOST;
74
} else {
75
t.c_iflag &= ~(BRKINT | INPCK | IGNBRK | ISTRIP | IGNCR | IXON | INLCR | PARMRK);
76
t.c_oflag &= ~OPOST;
77
}
78
79
t.c_cc[VMIN] = 1;
80
t.c_cc[VTIME] = 0;
81
82
//set the ttye info
83
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &t) == -1)
84
return; //TODO exception handling
85
}
86
87
88
int main()
89
{
90
int x;
91
92
setMode(0, 0, 1, 1);
93
94
do {
95
x = getkey();
96
printf("%d\n", x);
97
usleep(30000);
98
} while(hasInput());
99
return 0;
100
}
101
102