Hide password input on terminal

后端 未结 15 1391
清酒与你
清酒与你 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:33

    Your method is correct, however you'll need to turn off terminal echo while the password is being entered:

    #include 
    
    void echo_off()
    {
        struct sgttyb state;
        (void)ioctl(0, (int)TIOCGETP, (char *)&state);
        state.sg_flags &= ~ECHO;
        (void)ioctl(0, (int)TIOCSETP, (char *)&state);
    }
    
    void echo_on()
    {
        struct sgttyb state;
        (void)ioctl(0, (int)TIOCGETP, (char *)&state);
        state.sg_flags |= ECHO;
        (void)ioctl(0, (int)TIOCSETP, (char *)&state);
    }
    

    Instead of getch(), why not just use getc() instead?

提交回复
热议问题