如何使用c在终端中停止回声?

zen*_*god 1 c echo

假设我正在使用 fgets 读取一个字符串,并且我想防止该字符串的字符在终端内部回显(没有 bash 技巧)。我怎样才能做到这一点?

Ale*_*zub 5

假设您在 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类型。

  • 这涵盖了它,`fgetc`也允许使用掩码字符,请参阅[隐藏终端上的密码输入](/sf/ask/479964481/#32421674) (2认同)