kilo.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <ctype.h>
  2. #include <errno.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <termios.h>
  6. #include <unistd.h>
  7. struct termios orig_termios;
  8. void die(const char *s) {
  9. perror(s);
  10. exit(1);
  11. }
  12. void disableRawMode() {
  13. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
  14. die("tcsetattr");
  15. }
  16. void enableRawMode() {
  17. if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) die("tcgetattr");
  18. atexit(disableRawMode);
  19. struct termios raw = orig_termios;
  20. raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  21. raw.c_oflag &= ~(OPOST);
  22. raw.c_cflag |= (CS8);
  23. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
  24. raw.c_cc[VMIN] = 1;
  25. raw.c_cc[VTIME] = 0;
  26. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
  27. }
  28. int main() {
  29. enableRawMode();
  30. while (1) {
  31. char c = '\0';
  32. if (read(STDIN_FILENO, &c, 1) == -1 && errno != EAGAIN) die("read");
  33. if (iscntrl(c)) {
  34. printf("%d\r\n", c);
  35. } else {
  36. printf("%d ('%c')\r\n", c, c);
  37. }
  38. if (c == 'q') break;
  39. }
  40. return 0;
  41. }