-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkbhit.c
58 lines (46 loc) · 1.11 KB
/
kbhit.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
#include "kbhit.h"
/* fileno setbuf stdin */
#include <stdio.h>
/* NULL */
#include <stddef.h>
/* termios tcsetattr tcgetattr TCSANOW */
#include <termios.h>
/* ioctl FIONREAD ICANON ECHO */
#include <sys/ioctl.h>
static int initialized = 0;
static struct termios original_tty;
int kbhit()
{
if(!initialized)
{
kbinit();
}
int bytesWaiting;
ioctl(fileno(stdin), FIONREAD, &bytesWaiting);
return bytesWaiting;
}
/* Call this just when main() does its initialization. */
/* Note: kbhit will call this if it hasn't been done yet. */
void kbinit()
{
struct termios tty;
tcgetattr(fileno(stdin), &original_tty);
tty = original_tty;
/* Disable ICANON line buffering, and ECHO. */
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), TCSANOW, &tty);
/* Decouple the FILE*'s internal buffer. */
/* Rely on the OS buffer, probably 8192 bytes. */
setbuf(stdin, NULL);
initialized = 1;
}
/* Call this just before main() quits, to restore TTY settings! */
void kbfini()
{
if(initialized)
{
tcsetattr(fileno(stdin), TCSANOW, &original_tty);
initialized = 0;
}
}