简体   繁体   中英

Obscuring user input in command line programs

I'm writing a few functions for getting and storing a user password. It's all working OK but is there any way of replacing what is typed at the prompt with an asterisk, for example?

This is fairly standard behaviour in windowed applications I've had a good look through the C libraries but all of the fgets/getc type functions don't seem to offer any control over this.

EDIT: trying to do this with ANSI C, running on OS X. Answers below have pointed me in the right direction - my search didn't turn up a few of the links...

Assuming POSIX:

struct termios t;
tcgetattr(STDIN_FILENO, &t);
t.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &t);

Then no user input will be echoed. Set back the ECHO flag if you want to undo this.

Sure, use some kind of terminal control library to disable character echo and then print whatever you like. Possibilities:

You didn't say which platform or compiler, but see ANSI C No-echo keyboard input . Maybe getch() or kbhit() or getpass(), depending on environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM