在 C 中输入密码输入密码

2023-09-07 09:32:37 作者:没心没肺锝小女人

I am aware that it is not possible to echo the * while you type in standard ANSI C. But is there a way to display nothing while someone is typing their password in the console. What I mean is like the sudo prompts in a Unix/Linux terminal. Like if you type in the command: sudo cp /etc/somefile ~/somedir. You are usually prompted for the root password. And while you type it in, the terminal displays nothing. Is this effect possible in C? If it is, how?

解决方案

The function that you are looking for is: getpass(). You will note, though, that it is marked as "LEGACY". Although it isn't going to go anywhere, the function doesn't allow the size of the input buffer to be specified, which makes it not a very good interface. As Jefromi has noted, the glibc manual provides portable example code for implementing getpass from scratch in a way that allows an arbitrary input size (and isn't LEGACY).