手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2013-01-16] 来源:Linux社区  作者:aaa20090987 [字体:大 中 小]

以前在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;
}

int main()
{
 char password[MAXLEN];
 printf("Enter password: ");
 new_getpass(password, MAXLEN);
 printf("You password is: %s\n", password);
 return 0;
}

 

linux
相关资讯       Linux c 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款