使用tcgetattr函数和tcsetattr函数 解决密码回显问题。

使用tcgetattr函数和tcsetattr函数

还有种方法,可以不使用curses库解决密码输入的回显问题。程序p6.4.c通过使用tcgetattr函数和tcsetattr函数同样达到了目的。具体代码如下:

    

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

#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL)

//函数set_disp_mode用于控制是否开启输入回显功能
//如果option为0,则关闭回显,为1则打开回显
int set_disp_mode(int fd,int option)
{
int err;
struct termios term;

if(tcgetattr(fd,&term)==-1){
perror("Cannot get the attribution of the terminal");
return 1;
}

if(option)
term.c_lflag|=ECHOFLAGS;
else
term.c_lflag &=~ECHOFLAGS;

err=tcsetattr(fd,TCSAFLUSH,&term);
if(err==-1 && err==EINTR){
perror("Cannot set the attribution of the terminal");
return 1;
}

return 0;
}

//函数getpasswd用于获得用户输入的密码,并将其存储在指定的字符数组中
int getpasswd(char* passwd, int size)
{
int c;
int n = 0;

printf("Please Input password:");

do{
c=getchar();

if (c != '/n'|c!='/r'){
passwd[n++] = c;
}
}while(c != '/n' && c !='/r' && n < (size - 1));

passwd[n] = '/0';

return n;
}

int main()
{
char passwd[20];

//首先关闭输出回显,这样输入密码时就不会显示输入的字符信息
set_disp_mode(STDIN_FILENO,0);
//调用getpasswd函数获得用户输入的密码
getpasswd(passwd, sizeof(passwd));

printf("/nYour passwd is:%s/n", passwd);
printf("Press any key continue .../n");

set_disp_mode(STDIN_FILENO,1);
getchar();
return 0;
}

使用gcc编译p6.4.c代码,获得名为p6.4的可执行程序。执行该程序,得到如下的输出结果:

    

[program@localhost charter6]$ gcc -o p6.4 p6.4.c
[program@localhost charter6]$ ./p6.4
Please Input password:
Your passwd is:afdfasf

Press any key continue ...

[program@localhost charter6]$

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值