gpt4 book ai didi

c - 在不使用 getpass (3) 的情况下在 C 中获取密码?

转载 作者:行者123 更新时间:2023-12-01 02:46:57 26 4
gpt4 key购买 nike

我可以使用 getpass() 获取密码。但是,手册页说:

This function is obsolete. Do not use it.

以符合 POSIX 的方式从用户终端获取密码而不回显密码的当前方法是什么? [最初我说的是“可移植”,但我的意图是避免使用过时的功能。]

最佳答案

这应该适用于 linux/macosx,windows 版本应该使用 Get/Set ConsoleMode

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

int
main(int argc, char **argv)
{
struct termios oflags, nflags;
char password[64];

/* disabling echo */
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;

if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}

printf("password: ");
fgets(password, sizeof(password), stdin);
password[strlen(password) - 1] = 0;
printf("you typed '%s'\n", password);

/* restore terminal */
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}

return 0;
}

关于c - 在不使用 getpass (3) 的情况下在 C 中获取密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371186/

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