How can I make my program not echo input?
How can I make my program not echo input, like login does when asking for
your password?
There is an easy way, and a slightly harder way:
The easy way, is to use getpass()
, which is probably found on
almost all Unices. It takes a string to use as a prompt. It will read up
to an EOF
or newline and returns a pointer to a static area of
memory holding the string typed in.
The harder way is to use tcgetattr()
and tcsetattr()
, both
use a struct termios
to manipulate the terminal. The following
two routines should allow echoing, and non-echoing mode.
#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <string.h>
static struct termios stored_settings;
void echo_off(void)
{
struct termios new_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ECHO);
tcsetattr(0,TCSANOW,&new_settings);
return;
}
void echo_on(void)
{
tcsetattr(0,TCSANOW,&stored_settings);
return;
}
Both routines used, are defined by the POSIX standard.
Home | FAQ |