在敲代码的时候,密码回显是经常需要用到的,有的时候需要回显“*”,有的时候输入密码什么也没回显,例如linux的terminal下普通用户切换管理员输入密码的时候就什么也没提示。。下面提供输入密码回显“*”的C代码,如有不对望大家提出指正。
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
int inputpsword(char *pass)
{
int i,j;
char inletter;
struct termios term, termsave; //专门的结构体termios
int fd=-1;
fd=open("/dev/tty",O_RDWR|O_NOCTTY); //open一个tty句柄
if(fd<0) return -1;
tcgetattr(fd, &term); //将tty句柄属性get成结构体termios
tcgetattr(fd, &termsave);
term.c_lflag &= ~(ICANON|ECHO|ISIG);
tcsetattr(fd, TCSANOW, &termsave);
//向tty句柄输出任何字符前,必须先执行tcsetattr()
for(i=0;i<31;i++)
{
tcsetattr(fd, TCSANOW, &term);
read(fd, &inletter, 1);//读入口令
if(inletter!='\n')
{
pass[i]=inletter;
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"*",1); //回显口令,显示*
}
else
{
pass[i]='\0';
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"\n",1);
break;
}
}
if(i==31)
{
//到长度限制,手工对字符串变量结尾(’\0’),同时回显”\n”
pass[i]='\0';
tcsetattr(fd, TCSANOW, &termsave);
write(fd,"\n",1);
}
close(fd);
return 0;
}
int main()
{
char buff[6]="\0";
printf("请输入密码(<7位):\n");//注意边界问题.如越界了没有报错,那只是“犯罪了未被抓”而已
inputpsword(buff);
return 0;
}
程序运行结果: