Linux下编写c程序使输入的密码不回显问题

    #include <stdio.h>  
    #include <termios.h>  
    #include <unistd.h>  
    #include <errno.h>  
    #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)  
    //函数set_disp_mode用于控制是否开启输入回显功能  
    //如果option为0,则关闭回显,为1则打开回显  
    void set_disp_mode(int fd,int option)  
    {  
       int err;  
       struct termios term;  
       if(tcgetattr(fd,&term)==-1){  
         perror("Cannot get the attribution of the terminal");  
         return ;  
       }  
       if(option)  
            term.c_lflag|=ECHOFLAGS;  
       else  
            term.c_lflag &=~ECHOFLAGS;  
       err=tcsetattr(fd,TCSAFLUSH,&term);  
       if(err==-1 && err==EINTR){  
            perror("Cannot set the attribution of the terminal");  
            return ;  
       }  
       return ;  
    }  
    //函数getpasswd用于获得用户输入的密码,并将其存储在指定的字符数组中  
    void getpasswd(char* passwd, int size)  
    {  
       int c;  
       inti n = 0;  

       printf("Please Input password:");  

       do{  
          c=getchar();  
          if (c != '\n'|c!='\r'){  
             passwd[n++] = c;  
          }  
       }while(c != '\n' && c !='\r' && n < (size - 1));  
       passwd[n] = '\0';  
       return;  
    }  //比如现在定义一个char password[30];
    //当输入密码时,先调用  set_disp_mode(STDIN_FILENO,0); 
    //将系统设置为不回显模式,再调用 getpasswd(password, sizeof(password)),
    //输入密码,自然输入密码时,就不会在屏幕上出现你所输入的内容,但内容已经存入
    //password中了。当输入完成后,必须调用set_disp_mode(STDIN_FILENO,0);
    //函数关掉不回显,否则程序运行结束在终端输入命令时,就看不见输的命令是什么。
    //如下可以实现密码不回显:
       char* p;
       set_disp_mode(STDIN_FILENO,0);  
       getpasswd(password, sizeof(password));    
       p=password;  
       while(*p!='\n')  
         p++;  
       *p='\0';    
       set_disp_mode(STDIN_FILENO,1); 

猜你喜欢

转载自blog.csdn.net/qq_41681241/article/details/81112612