-1

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

Community
  • 1
  • 1
Sandeep Singh
  • 4,941
  • 8
  • 36
  • 56
  • 2
    I think this has already been solved here - http://stackoverflow.com/questions/6856635/hide-password-input-on-terminal – Rudolfs Bundulis Oct 17 '12 at 08:06
  • @RudolfsBundulis Yes, they discuss this indeed. The way to go would be this answer: http://stackoverflow.com/a/6869218/694576 – alk Oct 17 '12 at 08:25

2 Answers2

1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
0

The problem is getchar() waits until the user presses the enter key and then returns the whole string at once. What you want is a method to return immediately after a character has been typed. While there is no portable way to do this, for Windows you can #include <conio.h> in your application and replace array[counter++] = getchar() with array[counter++] = _getch() and it should work.

nickolayratchev
  • 1,136
  • 1
  • 6
  • 15