Tobiahao

SO1_TERMINAL_02

Jan 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.72 KB | None | 0 0
  1. /*
  2. Napisz program, który wyłączy echo, czyli wypisywanie znaków wprowadzonych z klawiatury na ekran. Po ponownym uruchomieniu program powinien
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <termios.h>
  9. #include <ctype.h>
  10. #include <string.h>
  11.  
  12. #define BUFFER_SIZE 128
  13.  
  14. void restore_settings(struct termios default_settings)
  15. {
  16.     if(tcsetattr(STDIN_FILENO, TCSANOW, &default_settings) == -1) {
  17.         perror("tcsetattr restore_settings");
  18.         exit(EXIT_FAILURE);
  19.     }
  20. }
  21.  
  22. void set_no_echo_mode(void)
  23. {
  24.     struct termios no_echo_attr;
  25.  
  26.     if(tcgetattr(STDIN_FILENO, &no_echo_attr) == -1) {
  27.         perror("tcgetattr set_no_echo_mode");
  28.         exit(EXIT_FAILURE);
  29.     }  
  30.  
  31.     no_echo_attr.c_lflag &= ~(ICANON | ECHO);
  32.     no_echo_attr.c_cc[VMIN] = 1;
  33.     no_echo_attr.c_cc[VTIME] = 0;
  34.    
  35.     if(tcsetattr(STDIN_FILENO, TCSANOW, &no_echo_attr) == -1) {
  36.         perror("tcsetattr set_no_echo_mode");
  37.         exit(EXIT_FAILURE);
  38.     }
  39. }
  40.  
  41. int main(void)
  42. {
  43.     struct termios default_settings;
  44.     char ch_buffer, asterisk = '*';
  45.     char passwd_buffer[BUFFER_SIZE];
  46.     unsigned int i = 0;
  47.     const char *enter_password = "Podaj haslo: ";
  48.  
  49.     if(!isatty(STDIN_FILENO)) {
  50.         perror("isatty");
  51.         return EXIT_FAILURE;
  52.     }
  53.  
  54.     if(tcgetattr(STDIN_FILENO, &default_settings) == -1) {
  55.         perror("tcgetattr");
  56.         return EXIT_FAILURE;
  57.     }
  58.  
  59.     write(STDOUT_FILENO, enter_password, strlen(enter_password));
  60.  
  61.     set_no_echo_mode();
  62.     while(read(STDIN_FILENO, &ch_buffer, 1) && (isalnum(ch_buffer) || (ispunct(ch_buffer))) && i < sizeof(passwd_buffer) -2) {
  63.         passwd_buffer[i++] = ch_buffer;
  64.         write(STDOUT_FILENO, &asterisk, 1);
  65.     }
  66.     passwd_buffer[i] = '\0';
  67.  
  68.     printf("\nPodane haslo: %s\n", passwd_buffer);
  69.  
  70.     restore_settings(default_settings);
  71.     return EXIT_SUCCESS;
  72. }
Add Comment
Please, Sign In to add comment