C语言 在Linux终端 对输入密码进行隐藏 回显******

本文介绍了一种在Linux终端中实现密码输入时隐藏显示的方法,并支持退格删除功能。通过自定义函数getpasswd实现了密码字符的隐藏及回显星号代替。

做了一个小工具,在Linux终端执行,其中需要输入用户名密码来登录。所以就想到了对输入的密码进行隐藏(支持退格回删)

/***************************************************************
File Name: test_pwd.c
Author: xiaohuo
Function List: main() 主函数
Created Time: 2018年7月3日
**************************************************************/

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

int mygetch()
{
    struct termios oldt, newt;
    int ch;
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    return ch;
}

int getpasswd(char *passwd, int size)
{
    int c, n = 0;
    do
    {
        c = mygetch();
        if (c != '\n' && c != 'r' && c != 127)
        {
            passwd[n] = c;
            printf("*");
            n++;
        }
        else if ((c != '\n' | c != '\r') && c == 127)//判断是否是回车或则退格
        {
            if (n > 0)
            {
                n--;
                printf("\b \b");//输出退格
            }
        }
    }while (c != '\n' && c != '\r' && n < (size - 1));
    passwd[n] = '\0';//消除一个多余的回车
    return n;
}

int main()
{
    char passWord[20];
    printf("请输入密码:\n");
    getpasswd(passWord, 20);
    printf("\n");
    printf("你输入的密码是:%s\n", passWord);
    return 0;
}

编译:

xiaohuo@zm:~/Tool$ gcc -o pwd test_pwd.c
xiaohuo@zm:~/Tool$

执行:

输入:1234/退格/5/回车

xiaohuo@zm:~/Tool$ ./pwd
请输入密码:
*****
你输入的密码是:1235
xiaohuo@zm:~/Tool$


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值