如何在c中屏蔽密码?

在C中,我想显示用户输入的每个字符*(例如,请输入您的密码:*****)

我在寻找,但无法找到解决方案。 我正在研究Ubuntu。 有人知道一个好方法吗?

看我的代码。 它适用于我的FC9 x86_64系统:

#include  #include  #include  #include  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; } 

看看ncurses库。 它是一个非常自由许可的库,在各种系统上都具有大量function。 我没有太多使用它,所以我不确定你想要调用哪些function,但如果看一下文档 ,我相信你会找到你想要的。

手动完成; 使用例如conio中的getch()一次读取一个字符输入,并为每个字符打印*。

使用像这样的程序问我更多的问题

此程序用于放置*而不是char,并在使用退格后^^删除输入

 #include  #include  #include  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); }