1. 程式人生 > >關於Linux終端 輸入密碼回顯******

關於Linux終端 輸入密碼回顯******

我們都知道,在Linux中:
char a[10] = {0};
scanf(”%s”, a);
在終端控制檯上輸入的字串(或者字元)都會在終端顯示出來,那麼當我們想輸入密碼時(並不想被別人看見)該怎麼辦呢?
(可以退格重新輸入密碼哦)
這裡寫圖片描述

/***************************************************************

File Name: mima.c
Author: 浮生流年
Function List: main() 主函式
Created Time: 2017年12月12日 星期二 13時37分13秒
**************************************************************

/

#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;
}