Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active April 14, 2017 13:57
Show Gist options
  • Save jdmichaud/67f20c0d1a6c1ebb97336fcc300f0659 to your computer and use it in GitHub Desktop.
Save jdmichaud/67f20c0d1a6c1ebb97336fcc300f0659 to your computer and use it in GitHub Desktop.
Print the key codes on the terminal as you type
// Inspired by http://viewsourcecode.org/snaptoken/kilo/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <ctype.h>
struct termios orig_termios;
void unsetupTerminal() {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios);
}
void setupTerminal() {
struct termios termios;
tcgetattr(STDIN_FILENO, &orig_termios);
termios = orig_termios;
// Turn off:
// ECHO: echo mode (don't print letter)
// ICANNON: canonical mode (don't wait for enter)
// ISIG: Ctrl-C /Ctrl-Z - send key combination to the application
// IEXTEN: Ctrl-V - send key combination to the application
termios.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
// Tirn off:
// IXON: Ctrl-S /Ctrl-Q - send key combination to the application
// ICRNL: Ctrl-M - send key combination to the application
termios.c_iflag &= ~(IXON | ICRNL);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios);
atexit(unsetupTerminal);
}
int main() {
char c;
setupTerminal();
while (read(STDIN_FILENO, &c, 1) == 1) {
if (iscntrl(c)) {
printf("%d\n", c);
} else {
printf("%d ('%c')\n", c, c);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment