我可以使用getpass()
来获取密码。然而,手册上说:
此函数已过时。不使用
它。
当前从用户终端获取密码的方法是什么,而不使用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/12580766/