Tobiahao

SO1_TERMINAL_03

Jan 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. /*
  2. Napisz program demonstrujący obsługę terminala w trybie niekanonicznym (Może to być np. program posiadający menu, które jest uaktywnione naciśnięciem klawisza, bez konieczności potwierdzania klawiszem Enter).
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <termios.h>
  9.  
  10. void restore_settings(struct termios default_settings)
  11. {
  12.     if(tcsetattr(STDIN_FILENO, TCSANOW, &default_settings) == -1) {
  13.         perror("tcsetattr restore_settings");
  14.         exit(EXIT_FAILURE);
  15.     }
  16. }
  17.  
  18. void set_no_echo_mode(void)
  19. {
  20.     struct termios attr;
  21.  
  22.     if(tcgetattr(STDIN_FILENO, &attr) == -1) {
  23.         perror("tcgetattr set_no_echo_mode");
  24.         exit(EXIT_FAILURE);
  25.     }
  26.  
  27.     attr.c_lflag &= ~(ICANON | ECHO);
  28.     attr.c_cc[VMIN] = 1;
  29.     attr.c_cc[VTIME] = 0;
  30.  
  31.     if(tcsetattr(STDIN_FILENO, TCSANOW, &attr) == -1) {
  32.         perror("tcsetattr set_no_echo_mode");
  33.         exit(EXIT_FAILURE);
  34.     }
  35. }
  36.  
  37. void draw_menu(void)
  38. {
  39.     char ch;
  40.     printf("1. Pierwsza opcja\n2. Druga opcja\n3. Trzecia opcja\n");
  41.  
  42.     read(STDIN_FILENO, &ch, 1);
  43.     switch(ch){
  44.         case '1':
  45.             printf("Wybrales pierwsza opcje!\n");
  46.             break;
  47.         case '2':
  48.             printf("Wybrales druga opcje!\n");
  49.             break;
  50.         case '3':
  51.             printf("Wybrales trzecia opcje!\n");
  52.             break;
  53.         default:
  54.             printf("Niepoprawny wybor!\n");
  55.     }
  56. }
  57.  
  58. int main(void)
  59. {
  60.     struct termios default_settings;
  61.  
  62.     if(!isatty(STDIN_FILENO)) {
  63.         perror("isatty");
  64.         return EXIT_FAILURE;
  65.     }
  66.  
  67.     if(tcgetattr(STDIN_FILENO, &default_settings) == -1) {
  68.         perror("tcgetattr main");
  69.         return EXIT_FAILURE;
  70.     }
  71.  
  72.     set_no_echo_mode();
  73.     draw_menu();
  74.     restore_settings(default_settings);
  75.  
  76.     return EXIT_SUCCESS;
  77. }
Add Comment
Please, Sign In to add comment