Hide password input on terminal

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

    You can create your own getch() function on Linux in this manner.

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

    Demo code:

    int main(int argc, char **argv) {
        int ch;
        printf("Press x to exit.\n\n");
        for (;;) {
            ch = getch();
            printf("ch = %c (%d)\n", ch, ch);
            if(ch == 'x')
                  break;
        }
        return 0;
    }
    

提交回复
热议问题