How to stop echo in terminal using c?

梦想与她 提交于 2021-02-05 08:04:16

问题


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?


回答1:


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.

Also this might probably not work for all tty types.



来源:https://stackoverflow.com/questions/59922972/how-to-stop-echo-in-terminal-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!