尝试将用户输入实时转换为星号
我正在编写一个小型 C 程序,要求用户输入密码,当用户通过键盘输入字符时,这些字符将显示为星号,当他们按下 Enter 键时,将显示实际密码。我尝试摆弄 getchar() 并分配变量,但没有得到所需的解决方案。任何指导表示赞赏,谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>
char *get_password();
int main() {
struct termios info;
tcgetattr(0, &info);
// info.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &info);
printf("Create a password: ");
int c = getchar();
c = '*';
char *password = get_password();
printf("You entered: %s\n", password);
tcgetattr(0, &info);
info.c_lflag |= ECHO;
tcsetattr(0, TCSANOW, &info);
}
#define BUFSIZE 100
char buf[BUFSIZE];
char *get_password() {
int c, len = 0;
while ((c = getchar()) != EOF && c != '\n') {
buf[len++] = c;
if (len == BUFSIZE - 1)
break;
}
buf[len] = 0;
putchar('\n');
return buf;
}
I am writing a small C program that asks a user for a password, as the user enters characters via keyboard, these characters will be displayed as asterisks and when they hit enter the actual password is displayed. I have tried fiddling with getchar()
and assigning variables but I am not getting the desired solution. Any guidance is appreciated, thanks.
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>
char *get_password();
int main() {
struct termios info;
tcgetattr(0, &info);
// info.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &info);
printf("Create a password: ");
int c = getchar();
c = '*';
char *password = get_password();
printf("You entered: %s\n", password);
tcgetattr(0, &info);
info.c_lflag |= ECHO;
tcsetattr(0, TCSANOW, &info);
}
#define BUFSIZE 100
char buf[BUFSIZE];
char *get_password() {
int c, len = 0;
while ((c = getchar()) != EOF && c != '\n') {
buf[len++] = c;
if (len == BUFSIZE - 1)
break;
}
buf[len] = 0;
putchar('\n');
return buf;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 @chqrlie 指出的,正确的密码处理需要禁用回显和缓冲。以下是执行此操作的快速步骤:
完成密码处理后,使用以下命令恢复正常行为:
As @chqrlie points out, proper password processing requires that echoing be disabled and buffering as well. Here are the quick steps to do that:
then after you're done with the password handling, restore the normal behavior with:
读取没有 echo 的密码比使用
getchar()
来摆弄要复杂一些:stdin
中的缓冲或直接读取字节来自低层系统句柄 0*;*) 从系统句柄 2 (
stderr
) 读取是从用户获取密码的有用替代方法,即使stdin
是从文件重定向的。这是一个带注释的实现:
Reading a password without echo is a bit more tricky than just fiddling with
getchar()
:stdin
or read bytes directly from the low level system handle 0*;*) Reading from system handle 2 (
stderr
) is a useful alternative to get the password from the user even ifstdin
is redirected from a file.Here is a commented implementation: