Reputation: 1174
Suppose I'm reading a string using fgets, and I want to prevent that string's characters from echoing in the terminal internally (no bash tricks). How can I do that?
Upvotes: 10
Views: 7338
Reputation: 2576
Assuming you're running on a POSIX-compatible OS, you need to play with local control terminal (termios) flags for stdin
using tcgetattr()
and tcsetattr()
:
#include <stdio.h>
#include <termios.h>
int main(int argc, char *argv[])
{
printf("Enter password: ");
struct termios term;
tcgetattr(fileno(stdin), &term);
term.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), 0, &term);
char passwd[32];
fgets(passwd, sizeof(passwd), stdin);
term.c_lflag |= ECHO;
tcsetattr(fileno(stdin), 0, &term);
printf("\nYour password is: %s\n", passwd);
}
You might want to disable additional flags during input. This is just an example. Beware of interrupts — you really want to reset the terminal state even if your program is interrupted.
Also this might probably not work for all tty
types.
Upvotes: 16