In C, I want to display 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. Does anybody know a good way?
In C, I want to display 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. Does anybody know a good way?
Do it manually; Read input one character at a time with for example getch() in conio, and print a * for each.
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;
}