因为在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;
}