#include #include #include #include /* * getpw1.c: get a password with echo off * shows how to change the terminal settings * note: press ^C during input (do this under dash, not bash) */ int turn_off_echo(int); int turn_on_echo(int); int read_a_string(int , char [], int ); #define SLEN 100 int main() { char str[SLEN]; printf("Type the secret word\n"); if ( turn_off_echo(0) == -1 ) /* fd 0 is stdin */ exit(1); if ( read_a_string(0, str, SLEN) == 0 ) printf("You typed the string: %s\n", str); if ( turn_on_echo(0) == -1 ) exit(1); return 0; } /* * read no more than len-1 chars into array, put a \0 at end * if last char is a \n, then remove that */ int read_a_string(int fd, char a[], int len) { int nread; nread = read(fd, a, len-1); if ( nread <= 0 ) return -1; if ( a[nread-1] == '\n' ) a[nread-1] = '\0'; else a[nread] = '\0'; return 0; } /* * get settings for fd, turn off the ECHO bit, set settings */ int turn_off_echo(int fd) { struct termios settings; if ( tcgetattr(fd, &settings) == -1 ) return -1; settings.c_lflag &= ~ECHO; /* turn off echo bit */ if ( tcsetattr(fd, TCSANOW, &settings) == -1 ) return -1; return 0; } /* * get settings for fd, turn on the ECHO bit, set settings */ int turn_on_echo(int fd) { struct termios settings; if ( tcgetattr(fd, &settings) == -1 ) return -1; settings.c_lflag |= ECHO; /* turn off echo bit */ if ( tcsetattr(fd, TCSANOW, &settings) == -1 ) return -1; return 0; }