I want to allow users to enter password using command-line interface. but I don't want to display this password on screen (or display "****").
How to do it in C? Thanks.
Update:
I'm working on Linux only. So I don't actually care about Win or other systems. I tried Lucas' solution and it worked fine. However, I still have another question:
If this is a single process & single thread app, changing setting of termios affects different terminals?
How about 1 process - multi threads, multi processes - multi threads?
Thanks very much.
If your system provides it, getpass is an option:
#include <unistd.h>
/* ... */
char *password = getpass("Password: ");
This will not display anything as characters are typed.
The function getpass is now obsolete. Use termios.
#include <termios.h>
#include <stdio.h>
void get_password(char *password)
{
static struct termios old_terminal;
static struct termios new_terminal;
//get settings of the actual terminal
tcgetattr(STDIN_FILENO, &old_terminal);
// do not echo the characters
new_terminal = old_terminal;
new_terminal.c_lflag &= ~(ECHO);
// set this as the new terminal options
tcsetattr(STDIN_FILENO, TCSANOW, &new_terminal);
// get the password
// the user can add chars and delete if he puts it wrong
// the input process is done when he hits the enter
// the \n is stored, we replace it with \0
if (fgets(password, BUFSIZ, stdin) == NULL)
password[0] = '\0';
else
password[strlen(password)-1] = '\0';
// go back to the old settings
tcsetattr(STDIN_FILENO, TCSANOW, &old_terminal);
}
int main(void)
{
char password[BUFSIZ];
puts("Insert password:");
get_password(password);
puts(password);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With