Linux下C语言键盘输入密码时无回显(屏幕不显示字符)


  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.     
  33.    printf("Please Input password:");  
  34.     
  35.    do{  
  36.       c=getchar();  
  37.       if (c != '\n'|c!='\r'){  
  38.          passwd[n++] = c;  
  39.       }  
  40.    }while(c != '\n' && c !='\r' && n < (size - 1));  
  41.    passwd[n] = '\0';  
  42.    return n;  
  43. }  
  44. int main()  
  45. {  
  46.    char *p,passwd[20],name[20];  
  47.    printf("Please Input name:");  
  48.    scanf("%s",name);  
  49.    getchar();//将回车符屏蔽掉   
  50.    //首先关闭输出回显,这样输入密码时就不会显示输入的字符信息   
  51.    set_disp_mode(STDIN_FILENO,0);  
  52.    //调用getpasswd函数获得用户输入的密码   
  53.    getpasswd(passwd, sizeof(passwd));    
  54.    p=passwd;  
  55.    while(*p!='\n')  
  56.      p++;  
  57.    *p='\0';  
  58.    printf("\nYour name is: %s",name);  
  59.    printf("\nYour passwd is: %s\n", passwd);  
  60.    printf("Press any key continue ...\n");  
  61.    set_disp_mode(STDIN_FILENO,1);  
  62.    getchar();  
  63.    return 0;  
  64. }  

运行结果:


说明:Linux下C编程遇到要输入密码的问题,可输入的时候密码总不能让人看见吧,本来想用getch()来解决输入密码无回显的问题的,不料Linux-C中不支持getch(),我也没有找到功能类似的函数代替,上面这个例子达到了预期的效果。

相关内容