cmd_term.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. *******************************************************************************
  3. \file cmd_term.c
  4. \brief Command-line interface to Bee2: terminal
  5. \project bee2/cmd
  6. \created 2022.06.08
  7. \version 2023.03.21
  8. \copyright The Bee2 authors
  9. \license Licensed under the Apache License, Version 2.0 (see LICENSE.txt).
  10. *******************************************************************************
  11. */
  12. #include "../cmd.h"
  13. /*
  14. *******************************************************************************
  15. Терминал
  16. \thanks
  17. https://www.flipcode.com/archives/_kbhit_for_Linux.shtml
  18. (Morgan McGuire [morgan@cs.brown.edu])
  19. https://stackoverflow.com/questions/29335758/using-kbhit-and-getch-on-linux
  20. https://askcodes.net/questions/how-to-implement-getch---function-of-c-in-linux-
  21. *******************************************************************************
  22. */
  23. #ifdef OS_UNIX
  24. #include <termios.h>
  25. #include <unistd.h>
  26. #include <stdio.h>
  27. #include <sys/ioctl.h>
  28. #include <sys/socket.h>
  29. bool_t cmdTermKbhit()
  30. {
  31. struct termios oldattr, newattr;
  32. int bytesWaiting;
  33. tcgetattr(STDIN_FILENO, &oldattr);
  34. newattr = oldattr;
  35. newattr.c_lflag &= ~(ICANON | ECHO);
  36. tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
  37. ioctl(STDIN_FILENO, FIONREAD, &bytesWaiting);
  38. tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
  39. return bytesWaiting > 0;
  40. }
  41. int cmdTermGetch()
  42. {
  43. struct termios oldattr, newattr;
  44. int ch;
  45. fflush(stdout);
  46. tcgetattr(STDIN_FILENO, &oldattr);
  47. newattr = oldattr;
  48. newattr.c_lflag &= ~(ICANON | ECHO);
  49. newattr.c_cc[VMIN] = 1;
  50. newattr.c_cc[VTIME] = 0;
  51. tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
  52. ch = getchar();
  53. tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
  54. return ch;
  55. }
  56. #elif defined OS_WIN
  57. #include <conio.h>
  58. bool_t cmdTermKbhit()
  59. {
  60. return _kbhit();
  61. }
  62. int cmdTermGetch()
  63. {
  64. return _getch();
  65. }
  66. #else
  67. bool_t cmdTermKbhit()
  68. {
  69. return FALSE;
  70. }
  71. int cmdTermGetch()
  72. {
  73. char ch;
  74. scanf(" %c", &ch);
  75. return ch;
  76. }
  77. #endif