Hide password input on terminal

后端 未结 15 1562
清酒与你
清酒与你 2020-11-22 09:55

I want to mask my password while writing it with *. I use Linux GCC for this code. I know one solution is to use getch() function like this

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 10:44

    In C you can use getpasswd() function which pretty much doing similar thing as stty in shell, example:

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        char acct[80], password[80];
    
        printf(“Account: “);
        fgets(acct, 80, stdin);
    
        acct[strlen(acct)-1] = 0; /* remove carriage return */
    
        strncpy(password, getpass(“Password: “), 80);
        printf(“You entered acct %s and pass %s\n”, acct, password);
    
        return 0;
    }
    

    Here is equivalent shell script which use stty (which changes the settings of your tty):

    save_state=$(stty -g)
    /bin/echo -n “Account: “
    read acct
    /bin/echo -n “Password: “
    stty -echo
    read password # this won’t echo
    stty “$save_state”
    echo “”
    echo account = $acct and password = $password
    

    Source: How can I read a password without echoing it in C?

提交回复
热议问题