如何使用c停止终端中的回声? [英] How to stop echo in terminal using c?

查看:52
本文介绍了如何使用c停止终端中的回声?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用fgets读取字符串,并且想防止该字符串的字符在终端内部内部回显(没有bash的把戏).我该怎么办?

Suppose I'm reading a string using fgets, and I want to prevent that string's characters from echoing in the terminal internally (no bash tricks). How can I do that?

推荐答案

假定您正在与POSIX兼容的操作系统上运行,则需要使用 stdin 的本地控制终端(termios)标志使用 tcgetattr() tcsetattr() :

Assuming you're running on a POSIX-compatible OS, you need to play with local control terminal (termios) flags for stdin using tcgetattr() and 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);
}

您可能想在输入期间禁用其他标志.这只是一个例子.当心中断-即使您的程序被中断,您也确实想重置终端状态.

You might want to disable additional flags during input. This is just an example. Beware of interrupts — you really want to reset the terminal state even if your program is interrupted.

此外,这可能不适用于所有 tty 类型.

Also this might probably not work for all tty types.

这篇关于如何使用c停止终端中的回声?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆