c - 如何在 C 中为密码的每个输入字符显示 * - 使字符不可见

标签 c

Possible Duplicate:
Hide password input on terminal

我想实现这个:

$Insert Pass:
User types: a (a immediately disappears & '*' takes its position on the shell)
On the Shell    : a
Intermediate O/P: * 

User types: b (b immediately disappears & '*' takes its position on the shell)
On the Shell    : *b
Intermediate O/P: **

User types: c (c immediately disappears & '*' takes its position on the shell)
On the Shell    : **c
Final O/P       : *** 

我尝试过以下方法:

#include <stdio.h>
#include <string.h>

#define SIZE 20

int main()
{

    char array[SIZE];
    int counter = 0;

    memset(array,'0',SIZE);

    while ((array[counter]!='\n')&&(counter<=SIZE-2))
    {
        array[counter++] = getchar();
        printf("\b\b");
        printf ("*");
    }

    printf("\nPassword: %s\n", array);

    return 0;
}

但是我无法实现预期的输出。此代码无法使用户键入的字符不可见并立即显示“*”。

有人可以指导我吗?

谢谢。

最诚挚的问候, 桑迪普·辛格

最佳答案

你的方法不起作用;即使您可以覆盖该字符,我也可以在 script(1) 等工具中运行您的命令并查看输出。

正确的解决方案是将终端从“cooked”模式切换为“raw”模式并关闭回显。

第一个更改将使您的程序看到键入的每个字符(否则,shell 将收集一行输入并在用户按下 Enter 键后将其发送到您的进程)。

第二个更改阻止 shell/终端打印用户键入的内容。

See this article如何做到这一点。

关于c - 如何在 C 中为密码的每个输入字符显示 * - 使字符不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929734/

相关文章:

C:从模式匹配中提取字符串和字符串终止的替代方法?

c++ - 为什么 printf ("%f",0);给出未定义的行为?

c - 与缓冲区溢出数学的基本混淆

c - 深入了解预定义功能

c++ - 写入文件,st_mtime 不变

c - C 结构中的 float 成员不起作用:Code::blocks IDE 问题

c - 有没有办法将字符串数组拆分为 token 上的字符串子数组

c - IP_DROP_MEMBERSHIP 行为不一致

c - union 数据类型字段行为

c - 我应该检查 malloc() 是否成功吗?