天天看點

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則打開回顯
int 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 1;
   }
   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 1;
   }
   return 0;
}
//函數getpasswd用于獲得使用者輸入的密碼,并将其存儲在指定的字元數組中
int getpasswd(char* passwd, int size)
{
   int c;
   int 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 n;
}
int main()
{
   char *p,passwd[20],name[20];
   printf("Please Input name:");
   scanf("%s",name);
   getchar();//将回車符屏蔽掉
   //首先關閉輸出回顯,這樣輸入密碼時就不會顯示輸入的字元資訊
   set_disp_mode(STDIN_FILENO,0);
   //調用getpasswd函數獲得使用者輸入的密碼
   getpasswd(passwd, sizeof(passwd));  
   p=passwd;
   while(*p!='\n')
     p++;
   *p='\0';
   printf("\nYour name is: %s",name);
   printf("\nYour passwd is: %s\n", passwd);
   printf("Press any key continue ...\n");
   set_disp_mode(STDIN_FILENO,1);
   getchar();
   return 0;
}
           

運作結果:

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

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