Panagiss
Panagiss

Reputation: 3740

C Masking Password with getch() using ncurses Library

I have this simple Program and i have achieved hiding password with *.

printf("Password: ");

initscr();
noecho();

char passwd[MAX_PASS]
int p=0; 
    do{ 
        passwd[p]=getch(); 
        if(passwd[p]!='\n'){ 
            printw("*"); 
        } 
        p++; 
    }while(passwd[p-1]!='\n'); 
    passwd[p-1]='\0';

endwin();

Im able to mask the password with '*' . The problem is that the first print won't show in my terminal, until endwin(); happens i think , when i get back what was printed in the terminal before..... any clues why and how im going to fix that? I mean, i want to show the first printf and the printf's before that.

Upvotes: 1

Views: 617

Answers (1)

Thomas Dickey
Thomas Dickey

Reputation: 54562

The comment by @anonmess is close: when initializing curses (in initscr), the terminal description's smcup and rmcup capabilities may cause the terminal to switch into alternate screen while in curses mode, and then back out, showing the Password: on the normal screen. Alternate-screen is an xterm feature that's copied into a lot of terminal emulators, but it confuses some people.

It's possible (but not a good idea) to do printf while in curses mode:

  • the printf output confuses ncurses (it doesn't know that the printf may have moved the cursor it will put text in the wrong place), and
  • printf is buffered, so you'd have to do an fflush(stdout) to even see the printf output.

ncurses does an fflush(stdout) before switching into curses mode, so your Password: does get flushed out to the normal screen. Before ncurses 6.0, it did not do that (curses output used the same output buffers as printf), but that turned out to be a bad idea (read the release notes for 6.0).

Upvotes: 1

Related Questions