前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Linux C语言实现输入密码显示星号-手动实现getch()

Linux C语言实现输入密码显示星号-手动实现getch()

作者头像
程序员小涛
发布2021-12-24 14:23:44
3.1K0
发布2021-12-24 14:23:44
举报
文章被收录于专栏:涛的程序人生

Linux C语言实现输入密码显示星号-手动实现getch()

废话不多说直接上代码 github传送门

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int getch(void);
void get_password(char *password);

int main()
{
    char password[20];
    get_password(password);
    printf("%s\n", password);

    return 0;
}

int getch(void)
{
    int ch;
    struct termios tm, tm_old;
    tcgetattr(STDIN_FILENO, &tm);
    tm_old = tm;
    tm.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &tm);
    ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &tm_old);
    return ch;
}

void get_password(char *password)
{
    int i = 0;
    char ch;

    printf("Enter password: ");
    while ((ch = getch()) != '\n')
    {
        if (ch == '\b')
        {
            if (i > 0)
            {
                printf("\b \b");
                i--;
            }
        }
        else
        {
            password[i] = ch;
            printf("*");
            i++;
        }
    }
    password[i] = '\0';
    printf("\n");
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/12/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Linux C语言实现输入密码显示星号-手动实现getch()
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档