Skip to content

Instantly share code, notes, and snippets.

@harryhanYuhao
Created May 26, 2023 08:20
Show Gist options
  • Save harryhanYuhao/fc6a64969f5a46421303230fa9509a5f to your computer and use it in GitHub Desktop.
Save harryhanYuhao/fc6a64969f5a46421303230fa9509a5f to your computer and use it in GitHub Desktop.
Enable Terminal Raw Mode
// Simple snippets to enable raw mode
// stdin is read as long as any key are pressed
// A simple testing function is included
// Note in raw mode "\n" is not interpreted with "\r" carriage return
// All "\n" shall be replaced with "\r\n" for normal effect
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
struct termios original;
void disableRAWMode(void) {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &original) == -1) {
perror("error occur in function disableRAWMode");
}
}
void enableRAWMode(void) {
struct termios raw;
if (tcgetattr(STDIN_FILENO, &raw) == -1) {
// STDIN_FILENO is the standard input
perror("tcgetattr");
}
if (tcgetattr(STDIN_FILENO, &original) == -1) {
perror("tcgetattr");
}
atexit(&disableRAWMode); // From <stdlib.h> Execute the function when the
// program exits.
raw.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN);
raw.c_iflag &= ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP);
raw.c_oflag &= ~(OPOST);
raw.c_cflag &= ~(CS8);
// raw.c_cc[VMIN] = 0; // what read() returns after timeout
// raw.c_cc[VTIME] = 1; // Timeout after 0.1 s
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) {
perror("tcsetattr");
}
}
int main() {
enableRAWMode();
char a = getchar();
printf("key code: %i\r\n", a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment