Hide password input on terminal

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

    #include 
    #include 
    
    static struct termios old, new;
    
    void initTermios(int echo) {
        tcgetattr(0, &old);
        new = old;
        new.c_lflag &= ~ICANON;
        new.c_lflag &= echo ? ECHO : ~ECHO;
        tcsetattr(0, TCSANOW, &new);
    }
    
    void resetTermios(void) {
        tcsetattr(0, TCSANOW, &old);
    }
    
    char getch_(int echo) {
        char ch;
        initTermios(echo);
        ch = getchar();
        resetTermios();
        return ch;
    }
    
    char getch(void) {
        return getch_(0);
    }
    
    int main(void) {
        char c;
        printf("(getch example) please type a letter...");
        c = getch();
        printf("\nYou typed: %c\n", c);
        return 0;
    }
    

    Just copy these snippet and use it. Hope it helped

提交回复
热议问题