Linux下用C语言来模拟密码输入

Linux大全评论993 views阅读模式

以前在Linux环境下,想输入密码(关闭回显)时都是用getpass函数,今天无意中看到手册上说:This function is obsolete.  Do not use it.

那我就自己实现一个类似的功能吧(功能相同,原理不同)

程序的思路很简单:关闭回显,读取输入,恢复设置。

上代码:

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

#define MAXLEN 256

//参数dest是目标字符串, maxlen是最大长度,
//如果输入超过了最大长度,则密码将会被截断
//成功返回0,否则返回-1
int new_getpass(char *dest, int maxlen)
{
 struct termios oldflags, newflags;
 int len;

 //设置终端为不回显模式
 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);
 len = strlen(dest);
 if( len > maxlen-1 )
  len = maxlen - 1;
 dest[len-1] = 0;

 //恢复原来的终端设置
 if (tcsetattr(fileno(stdin), TCSANOW, &oldflags) != 0)
 {
  perror("tcsetattr");
  return -1;
 }
 return 0;
}

企鹅博客
  • 本文由 发表于 2020年2月26日 05:02:50
  • 转载请务必保留本文链接:https://www.qieseo.com/177260.html

发表评论