Possible Duplicate:
Hide password input on terminal
I want to achieve this:
$Insert Pass:
User types: a (a immediately disappears & '*' takes its position on the shell)
On the Shell : a
Intermediate O/P: *
User types: b (b immediately disappears & '*' takes its position on the shell)
On the Shell : *b
Intermediate O/P: **
User types: c (c immediately disappears & '*' takes its position on the shell)
On the Shell : **c
Final O/P : ***
I have tried the following approach:
#include <stdio.h>
#include <string.h>
#define SIZE 20
int main()
{
char array[SIZE];
int counter = 0;
memset(array,'0',SIZE);
while ((array[counter]!='\n')&&(counter<=SIZE-2))
{
array[counter++] = getchar();
printf("\b\b");
printf ("*");
}
printf("\nPassword: %s\n", array);
return 0;
}
But I am unable to achieve the expected Output. This Code cannot make the User-Typed Characters invisible & display a ‘*’ immediately.
Can someone please guide me on this.
Thanks.
Best Regards,
Sandeep Singh
Your approach doesn’t work; even if you can overwrite the character, I could run your command in a tool like
script(1)and see the output.The correct solution is to switch the terminal from cooked to raw mode and turn echo off.
The first change will make your program see each character as it is typed (otherwise, the shell will collect one line of input and send it to your process after the user has pressed enter).
The second change prevents the shell/terminal from printing what the user types.
See this article how to do this.