I want to allow users to enter password using command-line interface. but I don't want to display this password on screen (or display "****").
How to do it in C? Thanks.
Update:
I'm working on Linux only. So I don't actually care about Win or other systems. I tried Lucas' solution and it worked fine. However, I still have another question:
If this is a single process & single thread app, changing setting of termios affects different terminals?
How about 1 process - multi threads, multi processes - multi threads?
Thanks very much.
To do this in a portable way you will need to use a standardized or de-facto standard library.
See
man 3 termios
andman 3 ncurses
.Here is a program that will work on Linux and other Unix systems...
A number of improvements are possible. Using termios would probably be better, and it would avoid the fork and possible security issues of system(). Using standard I/O to read the password would probably be better. (As written the typed newline would have to be deleted.) There is a getpass() function in Linux and some others however it is marked as "obsolete. Do not use it.". It might be a good idea to deal with SIGTSTP.
Overall, I might look for an existing solution that deals with all these little issues...
If your system provides it, getpass is an option:
This will not display anything as characters are typed.
If you are using a UNIX environment something like this can turn off the ECHO of the command-line.
For C/commandline/linux see:
see the coment in
getch
aboutnoecho
. I've never tried this myself.In bash if you use
read -s
it does not echo on the screen:The function getpass is now obsolete. Use termios.