tags:

views:

210

answers:

4

I am aware that it is not possible to echo the * while you type in standard ANSI C. But is there a way to display nothing while someone is typing their password in the console. What I mean is like the sudo prompts in a Unix/Linux terminal. Like if you type in the command: sudo cp /etc/somefile ~/somedir. You are usually prompted for the root password. And while you type it in, the terminal displays nothing. Is this effect possible in C? If it is, how?

+6  A: 

The function that you are looking for is: getpass(). You will note, though, that it is marked as "LEGACY". Although it isn't going to go anywhere, the function doesn't allow the size of the input buffer to be specified, which makes it not a very good interface. As Jefromi has noted, the glibc manual provides portable example code for implementing getpass from scratch in a way that allows an arbitrary input size (and isn't LEGACY).

Michael Aaron Safyan
The documentation for GNU libc's getpass also notes how you might approach writing your own: http://www.gnu.org/software/libc/manual/html_node/getpass.html
Jefromi
@Jefromi, thanks, duly noted. I shall edit my post.
Michael Aaron Safyan
A: 

*This is not ANSI C (Thanks Billy) sample

You can detect keypress with _kbhit(), then get the value using _getch(). Both function will not echo the content on screen.

#include <conio.h>          //For keyboard events
#include <stdio.h>          //Include this or iostream
#include <locale>           
int main()
{
    bool bContinue = true;
    char szBuffer[255] = {0};
    unsigned int nbufIndex = 0;
    while (bContinue)
    {
        if (_kbhit())
        {
            szBuffer[nbufIndex] = _getch();
            if (szBuffer[nbufIndex] == 0xD)
            {
                bContinue = false;
            }
            else
            {
                ++nbufIndex;
                printf("*");
            }
        }
    }
    printf("\n%s\n", szBuffer);
    return 0;
}
YeenFei
Note that this is not ANSI C.
Billy ONeal
I don't think `conio.h` is likely to be available if you're compiling on UNIX or Linux.
Mike Daniels
+2  A: 

sudo is written in C, so yes :). The getpass() function Safyan mentioned is probably what you want, but here's where the actual sudo tool does it if you're interested:

http://sudo.ws/repos/sudo/file/dc3bf870f91b/src/tgetpass.c#l70

Michael Mrozek
A: 

The poor-man's method of doing this is to read user input character by character, and after each character is received print out a backspace character followed by *. The output is technically sent to the console, but it is immediately erased and overwritten by an asterisk (often before that frame is even drawn to the screen). Note that this is not really a secure method and has several security holes, but for low-tech low-security applications, it works.

bta