假设我正在使用 fgets 读取一个字符串,并且我想防止该字符串的字符在终端内部回显(没有 bash 技巧)。我怎样才能做到这一点?
假设您在 POSIX 兼容的操作系统上运行,您需要使用本地控制终端 (termios) 标志来stdin使用tcgetattr()和tcsetattr():
#include <stdio.h>
#include <termios.h>
int main(int argc, char *argv[])
{
printf("Enter password: ");
struct termios term;
tcgetattr(fileno(stdin), &term);
term.c_lflag &= ~ECHO;
tcsetattr(fileno(stdin), 0, &term);
char passwd[32];
fgets(passwd, sizeof(passwd), stdin);
term.c_lflag |= ECHO;
tcsetattr(fileno(stdin), 0, &term);
printf("\nYour password is: %s\n", passwd);
}
Run Code Online (Sandbox Code Playgroud)
您可能希望在输入期间禁用其他标志。这只是一个例子。当心中断——即使你的程序被中断,你也确实想重置终端状态。
此外,这可能不适用于所有tty类型。