首页 / 操作系统 / Linux / Linux下C语言实现 密码不回显输入加强版
明天要做一个项目,涉及到账号密码的输入,看了网上很多例子,Linux下的<curses.h> getch()好像功能有怪异。关闭回显的功能好像也不是很好用。网上给的单纯的getch() 输入的时候只是关闭了回显,如果密码输入错误不能删除。小弟不才稍微研究了一下,写了一个加强版的,经过Linux下的测试通过,写的比较粗糙,献丑了。getch()参照网上给出的...#include<stdio.h>
#include<termios.h>
#include<unistd.h>
#include<assert.h>
#include<string.h>
int getch()
{
int c=0;
struct termios org_opts, new_opts;
int res=0;
//----- store old settings -----------
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
//---- set new terminal parms --------
memcpy(&new_opts, &org_opts, sizeof(new_opts));
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
//------ restore old settings ---------
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==0);
return c;
}
int main()
{
int i;
char pd[128],pd1[128];
char a;
printf("请输入密码:");
while(1)
{
for(i=0;;i++)
{
pd[i]=getch();
if(pd[i]=="
")
{
pd[i]=" ";
break;
}
if(pd[i]==127)
{
printf(" ");
i=i-2;
}
else
printf("*");
if(i<0)
pd[0]=" ";
}
printf("
请再次输入:");
for(i=0;;i++)
{
pd1[i]=getch();
if(pd1[i]=="
")
{
pd1[i]=" ";
break;
}
if(pd1[i]==127)
{
printf(" ");
i=i-2;
}
else
printf("*");
if(i<0)
pd1[0]=" ";
}
if(strcmp(pd,pd1)==0)
break;
else
{
printf("
您两次输入的密码不一致,请重新输入:
");
printf("请输入密码:");
}
}
printf("
您输入的密码是:[%s]
",pd);
}