程序的思路很简单:关闭回显,读取输入,恢复设置。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
int getpasswd(char *dest, int maxlen);
int main()
{
char pwd[100];
printf("请输入密码:");
getpasswd(pwd,sizeof(pwd));
printf("密码:%s\n",pwd);
return 0;
}
//参数dest是目标字符串, maxlen是最大长度,
//如果输入超过了最大长度,则密码将会被截断
//成功返回0,否则返回-1
int getpasswd(char *dest, int maxlen)
{
struct termios oldflags, newflags;
//设置终端为不回显模式
tcgetattr(fileno(stdin), &oldflags);
newflags = oldflags;
newflags.c_lflag &= ~ECHO;
newflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &newflags) != 0)
{
perror("tcsetattr");
return -1;
}
//获取来自键盘的输入
fgets(dest, maxlen, stdin);
if(dest[strlen(dest)-1]=='\n')
dest[strlen(dest)-1]='\0';
//恢复原来的终端设置
if (tcsetattr(fileno(stdin), TCSANOW, &oldflags) != 0)
{
perror("tcsetattr");
return -1;
}
return 0;
}