Skip to content

Instantly share code, notes, and snippets.

@tlorens
Created September 11, 2014 12:45
Show Gist options
  • Select an option

  • Save tlorens/7ed6efc733b4f377fc4d to your computer and use it in GitHub Desktop.

Select an option

Save tlorens/7ed6efc733b4f377fc4d to your computer and use it in GitHub Desktop.
Capture single key input and continue in C
#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