gpt4 book ai didi

c - 隐藏终端上的密码输入

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:35 26 4
gpt4 key购买 nike

我想在用 * 编写密码时隐藏我的密码。我将 Linux GCC 用于此代码。我知道一种解决方案是像这样使用 getch() 函数

#include <conio.h>   
int main()
{
char c,password[10];
int i;
while( (c=getch())!= '\n');{
password[i] = c;
printf("*");
i++;
}
return 1;
}

但问题是 GCC 不包含 conio.h 文件,所以 getch() 对我没用。有人有解决方案吗?

最佳答案

在 Linux 世界中,屏蔽通常不使用星号,通常只是关闭回显并且终端显示空白如果您使用 su 或登录虚拟终端等

有一个处理获取密码的库函数,它不会用星号屏蔽密码,但会禁用将密码回显到终端。我从我拥有的一本 Linux 书籍中提取了这个。我相信它是 posix 标准的一部分

#include <unistd.h>
char *getpass(const char *prompt);

/*Returns pointer to statically allocated input password string
on success, or NULL on error*/

The getpass() function first disables echoing and all processing of terminal special characters (such as the interrupt character, normally Control-C).

It then prints the string pointed to by prompt, and reads a line of input, returning the null-terminated input string with the trailing newline stripped, as its function result.

谷歌搜索 getpass() 有一个 GNU 实现的引用(应该在大多数 linux 发行版中)和一些示例代码用于实现你自己的如果需要的话

http://www.gnu.org/s/hello/manual/libc/getpass.html

他们自己滚动的例子:

#include <termios.h>
#include <stdio.h>

ssize_t
my_getpass (char **lineptr, size_t *n, FILE *stream)
{
struct termios old, new;
int nread;

/* Turn echoing off and fail if we can't. */
if (tcgetattr (fileno (stream), &old) != 0)
return -1;
new = old;
new.c_lflag &= ~ECHO;
if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0)
return -1;

/* Read the password. */
nread = getline (lineptr, n, stream);

/* Restore terminal. */
(void) tcsetattr (fileno (stream), TCSAFLUSH, &old);

return nread;
}

如果需要,您可以以此为基础修改它以显示星号。

关于c - 隐藏终端上的密码输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54364529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com