我想允许用户通过命令行界面输入密码,但不想在屏幕上显示密码(或显示“****”)。
如何在C语言中做到这一点? 谢谢。
更新:
我只在Linux上工作。所以我实际上并不关心Win或其他系统。我尝试了Lucas的解决方案,它很好用。然而,我还有另一个问题:
如果这是一个单进程和单线程的应用程序,更改termios的设置会影响不同的终端吗?
对于单进程-多线程、多进程-多线程的情况呢?
非常感谢。
如果您的系统支持它,getpass 是一种选择:
#include <unistd.h>
/* ... */
char *password = getpass("Password: ");
由于字符被输入时不会显示任何内容。
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#define SIZE 100
void getPassword(char password[])
{
static struct termios oldt, newt;
int i = 0;
int c;
/*saving the old settings of STDIN_FILENO and copy settings for resetting*/
tcgetattr( STDIN_FILENO, &oldt);
newt = oldt;
/*setting the approriate bit in the termios struct*/
newt.c_lflag &= ~(ECHO);
/*setting the new bits*/
tcsetattr( STDIN_FILENO, TCSANOW, &newt);
/*reading the password from the console*/
while ((c = getchar())!= '\n' && c != EOF && i < SIZE){
password[i++] = c;
}
password[i] = '\0';
/*resetting our old STDIN_FILENO*/
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
}
int main(void)
{
char password[SIZE];
printf("please enter password\n");
getPassword(password);
printf("Do something with the password <<%s>>\n", password);
return 0;
}
#include <termios.h>
#include <stdio.h>
void get_password(char *password)
{
static struct termios old_terminal;
static struct termios new_terminal;
//get settings of the actual terminal
tcgetattr(STDIN_FILENO, &old_terminal);
// do not echo the characters
new_terminal = old_terminal;
new_terminal.c_lflag &= ~(ECHO);
// set this as the new terminal options
tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal);
// get the password
// the user can add chars and delete if he puts it wrong
// the input process is done when he hits the enter
// the \n is stored, we replace it with \0
if (fgets(password, BUFSIZ, stdin) == NULL)
password[0] = '\0';
else
password[strlen(password)-1] = '\0';
// go back to the old settings
tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal);
}
int main(void)
{
char password[BUFSIZ];
puts("Insert password:");
get_password(password);
puts(password);
}
对于C语言/命令行/Linux,请参考以下内容:
man getch
man noecho
请看getch
中关于noecho
的注释。我自己从未尝试过。
在bash中,如果你使用read -s
,它不会在屏幕上回显:
> read -s x
<type something><enter>
> echo $x
<whatever you typed>
#include <stdio.h>
int main(void) {
int f = open("/dev/tty", 0);
char s[100];
system("stty -echo > /dev/tty");
f >= 0 && read(f, s, sizeof s) > 0 && printf("password was %s", s);
system("stty echo > /dev/tty");
return 0;
}
#include<conio.h>
#include<iostream>
using namespace std;
int main(){
char *pass = new char[20];
cout<<"Password :";
int i=0;
while( ( pass[i]=getch() ) != '\n' && pass[i] != '\r' && i<19 )
{putchar('*'); i++;}
pass[i]='\0';
cout<<endl;
if(strcmp("123456789",pass)==0 ) // do stuff
return 0;}
std::cin
中读取密码。 - Jonathan Graehl