Skip to content

Instantly share code, notes, and snippets.

@devendranaga
Created January 30, 2019 03:51
Show Gist options
  • Save devendranaga/cb13f6661089845d85b5e3edf220f182 to your computer and use it in GitHub Desktop.
Save devendranaga/cb13f6661089845d85b5e3edf220f182 to your computer and use it in GitHub Desktop.
detect arrow keys in linux
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int getch (void)
{
int ch;
struct termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
int main()
{
while (1) {
int p = getch();
if (p == 65) {
printf("\narrow up\n");
} else if (p == 66) {
printf("arrow down\n");
} else if (p == 67) {
printf("arrow right\n");
} else if (p == 68) {
printf("arrow left\n");
} else if ((p != 27) && (p != 91)) {
putchar(p);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment