歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下C語言鍵盤輸入密碼時無回顯(屏幕不顯示字符)

Linux下C語言鍵盤輸入密碼時無回顯(屏幕不顯示字符)

日期:2017/3/1 10:31:21   编辑:Linux編程
  1. #include <stdio.h>
  2. #include <termios.h>
  3. #include <unistd.h>
  4. #include <errno.h>
  5. #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)
  6. //函數set_disp_mode用於控制是否開啟輸入回顯功能
  7. //如果option為0,則關閉回顯,為1則打開回顯
  8. int set_disp_mode(int fd,int option)
  9. {
  10. int err;
  11. struct termios term;
  12. if(tcgetattr(fd,&term)==-1){
  13. perror("Cannot get the attribution of the terminal");
  14. return 1;
  15. }
  16. if(option)
  17. term.c_lflag|=ECHOFLAGS;
  18. else
  19. term.c_lflag &=~ECHOFLAGS;
  20. err=tcsetattr(fd,TCSAFLUSH,&term);
  21. if(err==-1 && err==EINTR){
  22. perror("Cannot set the attribution of the terminal");
  23. return 1;
  24. }
  25. return 0;
  26. }
  27. //函數getpasswd用於獲得用戶輸入的密碼,並將其存儲在指定的字符數組中
  28. int getpasswd(char* passwd, int size)
  29. {
  30. int c;
  31. int n = 0;
  32. printf("Please Input password:");
  33. do{
  34. c=getchar();
  35. if (c != '\n'|c!='\r'){
  36. passwd[n++] = c;
  37. }
  38. }while(c != '\n' && c !='\r' && n < (size - 1));
  39. passwd[n] = '\0';
  40. return n;
  41. }
  42. int main()
  43. {
  44. char *p,passwd[20],name[20];
  45. printf("Please Input name:");
  46. scanf("%s",name);
  47. getchar();//將回車符屏蔽掉
  48. //首先關閉輸出回顯,這樣輸入密碼時就不會顯示輸入的字符信息
  49. set_disp_mode(STDIN_FILENO,0);
  50. //調用getpasswd函數獲得用戶輸入的密碼
  51. getpasswd(passwd, sizeof(passwd));
  52. p=passwd;
  53. while(*p!='\n')
  54. p++;
  55. *p='\0';
  56. printf("\nYour name is: %s",name);
  57. printf("\nYour passwd is: %s\n", passwd);
  58. printf("Press any key continue ...\n");
  59. set_disp_mode(STDIN_FILENO,1);
  60. getchar();
  61. return 0;
  62. }

運行結果:


說明:Linux下C編程遇到要輸入密碼的問題,可輸入的時候密碼總不能讓人看見吧,本來想用getch()來解決輸入密碼無回顯的問題的,不料Linux-C中不支持getch(),我也沒有找到功能類似的函數代替,上面這個例子達到了預期的效果。

Copyright © Linux教程網 All Rights Reserved