开发者

How to mask password in c?

In C, I want to displa开发者_如何转开发y every single character that the user type as * (Ex, Please type in your password: *****)

I'm searching around but can't be able to find a solution for this. I'm working on Ubuntu. Does anybody know a good way?


Take a look at the ncurses library. It's a very liberally licensed library with a huge amount of functionality on a large variety of systems. I haven't used it very much, so I'm not sure exactly which functions you'd want to call, but if take a look at the documentation, I'm sure you'll find what you want.


See my code. it works on my FC9 x86_64 system:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>

int main(int argc, char **argv)
{
        char passwd[16];
        char *in = passwd;
        struct termios  tty_orig;
        char c;
        tcgetattr( STDIN_FILENO, &tty_orig );
        struct termios  tty_work = tty_orig;

        puts("Please input password:");
        tty_work.c_lflag &= ~( ECHO | ICANON );  // | ISIG );
        tty_work.c_cc[ VMIN ]  = 1;
        tty_work.c_cc[ VTIME ] = 0;
        tcsetattr( STDIN_FILENO, TCSAFLUSH, &tty_work );

        while (1) {
                if (read(STDIN_FILENO, &c, sizeof c) > 0) {
                        if ('\n' == c) {
                                break;
                        }
                        *in++ = c;
                        write(STDOUT_FILENO, "*", 1);
                }
        }

        tcsetattr( STDIN_FILENO, TCSAFLUSH, &tty_orig );

        *in = '\0';
        fputc('\n', stdout);

        // if you want to see the result: 
        // printf("Got password: %s\n", passwd);

        return 0;
}


use a program like this one ask me for more questions

this program is used to put * instead of the char and it deletes the input after using backspace ^^

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
    char a[100],c;
    int i;
    fflush(stdin);
    for ( i = 0 ; i<100 ; i++ )
    {

        fflush(stdin);
        c = getch();
        a[i] = c;
        if ( a[i] == '\b')
        {
            printf("\b \b");
            i-= 2;
            continue;
        }
        if ( a[i] == ' ' || a[i] == '\r' )
            printf(" ");
        else
            printf("*");
        if ( a[i]=='\r')
            break;
    }
    a[i]='\0';

    printf("\n%s" , a);
}


Do it manually; Read input one character at a time with for example getch() in conio, and print a * for each.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜