Created
September 11, 2014 12:45
-
-
Save tlorens/7ed6efc733b4f377fc4d to your computer and use it in GitHub Desktop.
Capture single key input and continue in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <string.h> | |
| #include <sys/time.h> | |
| #include <termios.h> | |
| #include <stdlib.h> | |
| static struct termios g_old_kbd_mode; | |
| static int kbhit(void) { | |
| struct timeval timeout; | |
| fd_set read_handles; | |
| int status; | |
| FD_ZERO(&read_handles); | |
| FD_SET(0, &read_handles); | |
| timeout.tv_sec = timeout.tv_usec = 0; | |
| status = select(0 + 1, &read_handles, NULL, NULL, &timeout); | |
| return status; | |
| } | |
| static void old_attr(void) { | |
| tcsetattr(0, TCSANOW, &g_old_kbd_mode); | |
| } | |
| int getch( void ) { | |
| char ch; | |
| struct termios new_kbd_mode; | |
| tcgetattr(0, &g_old_kbd_mode); | |
| memcpy(&new_kbd_mode, &g_old_kbd_mode, sizeof(struct termios)); | |
| new_kbd_mode.c_lflag &= ~(ICANON | ECHO); | |
| new_kbd_mode.c_cc[VTIME] = 0; | |
| new_kbd_mode.c_cc[VMIN] = 1; | |
| tcsetattr(0, TCSANOW, &new_kbd_mode); | |
| atexit(old_attr); | |
| while (!kbhit()) | |
| { | |
| ch = getchar(); | |
| printf("[%c]", ch); | |
| if (ch == 'q') | |
| { | |
| exit(1); | |
| } | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment