#include #include #include #include #include /* * How to read a password of up to 256 charaqcters and prevent * the characters from being displayed. */ /* Maximum number of characters allowed for the password entered */ #define NUM_CHARACTERS 256 /* Reads a password but turns off the echoing of characters */ const char* get_passstring(const char *prompt) { struct termio save_tty; int ch; char *p; FILE *fp; FILE *outfp; /* points to either /dev/tty or stderr */ int fd; tcflag_t svlflag; static char input_buf[NUM_CHARACTERS + 1]; /* Try to read and write to /dev/tty */ fd = open("/dev/tty", O_RDWR); if (fd < 0 || (outfp = fp = fdopen(fd, "r+")) == NULL) { /* Can't read/write to /dev/tty, try to read from stdin and write * to stderr. */ outfp = stderr; fp = stdin; } ioctl(fileno(fp), TCGETA, &save_tty); /* Get terminal attributes */ svlflag = save_tty.c_lflag; /* Save current settings */ save_tty.c_lflag &= ~ECHO; /* Turn off character echoing */ ioctl(fileno(fp), TCSETA, &save_tty); /* Save these settings */ fprintf(outfp, "%s", prompt); rewind(outfp); /* rewind has an implied flush */ for (p = input_buf; p < &input_buf[NUM_CHARACTERS]; p++) { if ((ch = getc(fp)) == EOF || ch == '\n') { break; } *p = ch; } *p = '\0'; write(fileno(outfp), "\n", 1); /* Put in a visible newline */ save_tty.c_lflag = svlflag; /* Restore original settings */ ioctl(fileno(fp), TCSETA, &save_tty); /* Save these settings */ if (fp != stdin) { fclose(fp); } return input_buf; } int main(int argc, char *argv[]) { const char *p = get_passstring("Enter password: "); printf("The password entered is '%s'\n", p); }