kilo.c 1.1 KB

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