forked from cinsk/snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getch.c
63 lines (49 loc) · 911 Bytes
/
getch.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include "getch.h"
int
getch_(int nonblock, int peek)
{
struct termios oldt, newt;
int ch;
int oldf;
int ifd = fileno(stdin);
#ifdef GETCH_CHECK_TERM
if (isatty(ifd) != 0) {
errno = EBADFD;
return EOF;
}
#endif /* GETCH_CHECK_TERM */
tcgetattr(ifd, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(ifd, TCSANOW, &newt);
if (nonblock) {
oldf = fcntl(ifd, F_GETFL, 0);
fcntl(ifd, F_SETFL, oldf | O_NONBLOCK);
}
ch = getchar();
tcsetattr(ifd, TCSANOW, &oldt);
if (nonblock)
fcntl(ifd, F_SETFL, oldf);
if (peek && ch != EOF) {
ungetc(ch, stdin);
}
return ch;
}
#ifdef TEST_GETCH
int
main(void)
{
int ch;
while (1) {
ch = getch();
if (ch != EOF)
printf("%d\n", ch);
}
return 0;
}
#endif /* TEST_GETCH */