Linux 下设置输入不回显(可用于登录框输入密码)

因为在linux下没有getch()函数,所以在实现不回显功能的时候,需要用到

tcgetattr 和 tcsetattr 

其中

tcgetattr :获取终端的相关参数

tcsetattr  :设置终端参数



头文件:#include <termios.h>



函数原型: 

int tcgetattr(int fd,struct termios *termios_p);

int tcsetattr(int fd,int optional_actions,const struct termios *termios_p);



其中:

fd: 终端的文件描述符

struct termios : 获取与终端相关的参数



struct termios

{

    tcflag_t c_iflag;

    tcflag_t c_oflag;

    tcflag_t c_cflag;

    tcflag_t c_lflag;

    cc_t c_cc[NCCS];

};

 

optional_actions :控制修改起作用的时间

TCSANOW:不等数据传输完毕就立刻改变属性

TCSADRAIN:等待所有数据传输完毕才改变属性

TCSAFLUSH:清空输入输出缓冲区才改变属性

示例代码:
//测试linux下输入字符不回显

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

int main()
{
	char password[10];
	int i = 0;
	
	char ch;
	
	struct termios oldt,newt;
	
	while(1)
	{
		tcgetattr(STDIN_FILENO,&oldt);
		newt = oldt;
		
		newt.c_lflag &= ~(ECHO | ICANON);
		
		tcsetattr(STDIN_FILENO,TCSANOW,&newt);
		
		ch = getchar();
		
		if(ch == '\n')
		{
			password[10] = '\0';
			tcsetattr(STDIN_FILENO,TCSANOW,&oldt);
			break;
		}
		
		password[i] = ch;
		i++;
		
		tcsetattr(STDIN_FILENO,TCSANOW,&oldt);//每次输入一个字符后恢复回显状态
		printf("*");
	}
	
	return 0;
	
}
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>

int main()
{
	struct termios old,new;
	
	char password[8] = {0};	
	char ch;
	int  i = 0;
	
	tcgetattr(0,&old);
	new = old;
	
	new.c_lflag &= ~(ECHO | ICANON);
	
	printf("请输入密码....\n");
	
	while(1)
	{
		tcsetattr(0,TCSANOW,&new);
		
		scanf("%c",&ch);
		
		tcsetattr(0,TCSANOW,&old);
		
		if(i == 8 || ch == '\n')
		{
			break;
		}
		
		password[i] = ch;
		printf("*");
		
		i++;
	}
	
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值