2009-11-18 105 views
1

在C,我想顯示的每一個字符,用戶類型爲* (防爆,請輸入您的密碼:*****)如何在c中掩蓋密碼?

我四處尋找,但能不能找到解決方案。 我正在使用Ubuntu。有人知道一個好方法嗎?

+1

你的意思只是在命令行或特定的gui?例如,在Windows中,本地編輯框可以自動完成此操作。 – justinhj 2009-11-18 06:18:35

+0

在命令行 – root 2009-11-18 06:24:37

+1

閱讀http://www.gnu.org/software/coreutils/manual/libc/getpass.html – sambowry 2009-11-18 06:51:27

回答

2

查看我的代碼。它的工作原理我FC9 x86_64的系統上:

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <termios.h> 

int main(int argc, char **argv) 
{ 
     char passwd[16]; 
     char *in = passwd; 
     struct termios tty_orig; 
     char c; 
     tcgetattr(STDIN_FILENO, &tty_orig); 
     struct termios tty_work = tty_orig; 

     puts("Please input password:"); 
     tty_work.c_lflag &= ~(ECHO | ICANON); // | ISIG); 
     tty_work.c_cc[ VMIN ] = 1; 
     tty_work.c_cc[ VTIME ] = 0; 
     tcsetattr(STDIN_FILENO, TCSAFLUSH, &tty_work); 

     while (1) { 
       if (read(STDIN_FILENO, &c, sizeof c) > 0) { 
         if ('\n' == c) { 
           break; 
         } 
         *in++ = c; 
         write(STDOUT_FILENO, "*", 1); 
       } 
     } 

     tcsetattr(STDIN_FILENO, TCSAFLUSH, &tty_orig); 

     *in = '\0'; 
     fputc('\n', stdout); 

     // if you want to see the result: 
     // printf("Got password: %s\n", passwd); 

     return 0; 
} 
+0

使用此代碼,如果用戶輸入退格鍵,它將顯示爲*。在通過寫入(STDOUT_FILENO,「*」,1)寫入後,是否有支持通過退格鍵刪除輸入的方法? – 2011-01-28 16:18:51

0

手動操作;每次讀取輸入一個字符,例如conio中的getch(),併爲每個字符打印一個*。

+1

conio.h是windows中的頭文件。 我使用的是Ubuntu。我該怎麼做? – root 2009-11-18 06:28:09

+0

然後你可能會想要使用一個curses庫。 – 2009-11-18 06:38:02

3

查看ncurses庫。這是一個非常寬鬆的許可證庫,在各種系統上有大量的功能。我沒有用過它,所以我不確定你想要調用哪些函數,但是如果看看documentation,我相信你會找到你想要的。

0

使用這樣一個 程序問我更多的問題

這個程序是用來放*代替char和它使用退格鍵後刪除輸入^^

#include <stdio.h> 
#include <stdlib.h> 
#include <conio.h> 

int main() 
{ 
    char a[100],c; 
    int i; 
    fflush(stdin); 
    for (i = 0 ; i<100 ; i++) 
    { 

     fflush(stdin); 
     c = getch(); 
     a[i] = c; 
     if (a[i] == '\b') 
     { 
      printf("\b \b"); 
      i-= 2; 
      continue; 
     } 
     if (a[i] == ' ' || a[i] == '\r') 
      printf(" "); 
     else 
      printf("*"); 
     if (a[i]=='\r') 
      break; 
    } 
    a[i]='\0'; 

    printf("\n%s" , a); 
}