Link to home
Start Free TrialLog in
Avatar of ginrai
ginrai

asked on

password mask implemented in c program

Dear all,

I have a c program that accpts a sequence of chars from UNIX prompt for user
to enter password

char identifier [21];
fgets(identifier, 21, stdin);

However I want when the user type his/her password in the prompt

'*' will appear instead of echo the things user type.

Is there any code can do the above?

Thank you very much.

Regards,
Ginrai
Avatar of akshayxx
akshayxx
Flag of United States of America image

have a look at this .. this doesnt echo * .. but it disables echoing
it may not be a standard function these days
http://osr5doc.ca.caldera.com:457/cgi-bin/man/man?getpasswd+S
Avatar of grg99
grg99

Depends on the system you are doing this on.

On Unix, it might work to do a system( "stty -echo" ) to turn off character echoing.  

Oh, and if you want to echo a "*" in real-time, you'll also need system( "stty -raw" ) or somesuch so you get each character as typed.

This is a big nasty as you have to undo these when your program exits.  If your program bombs, you'd better have an exit procedure or try...except block to catch the error and reset things.

Regards,

grg99
>> Is there any code can do the above?

Try this,

char pass[25];
input( pass, 25 );

...

void input( char* buffer, int length )
{
    int pos = 0;
    char c;
 
    buffer[0] = '\0';

    while( ( c = getch() ) != 13 )
    {
        if( c != 8 && pos < ( length - 1 ) )
        {
            printf("*");
            buffer[pos] = c;
            pos++;
        }
        else if( pos != 0 )
        {
            printf("%c %c",8,8);
            pos--;
        }
    }
     buffer[pos] = '\0';
}

Exceter
>> else if( pos != 0 )

Sorry, this line should be,

else if( pos != 0 && c == 8 )

Exceter
Avatar of ginrai

ASKER

Dear Exceter,

I've tried the code but it does not work, it still echo the character I typed and put some * after I press enter.

Regards,
Ginrai
ASKER CERTIFIED SOLUTION
Avatar of Exceter
Exceter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ginrai

ASKER

Thank you, Exceter
Why the B?