Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ubuntu terminal, read from console in C but don't print on the screen the text I read

I am using Ubuntu and C with VS Code, I want to read a text from stdin but after I am done reading I don’t want the text I read to appear on the screen/terminal.
Also I want to see the letters that I am reading but after I am done, I don’t want to see the string on the screen.

I have used the code below but I am not getting the results I want as I want to see the characters that I am reading:

    /* get terminal attributes */
    struct termios termios;
    tcgetattr(STDIN_FILENO, &termios);

    /* disable echo */
    termios.c_lflag &= ~ECHO;
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To rephrase your purpose, you want the input to be erased after you hit the Enter key.

You can do this using ANSI escape sequences. Here is an example:

#include <stdio.h>
#include <string.h>

int main() {
    char phrase[100];

    printf("Enter passphrase: ");
    if (!fgets(phrase, sizeof phrase, stdin))
        return 1;
    phrase[strcspn(phrase, "\n")] = '\0'; // strip the newline if any

    printf("\033[F\r");   // back up one line
    printf("Enter passphrase: "); // output the prompt on top of itself
    printf("\033[K\r\n"); // erase end of line, move to next line

    printf("\nPass phrase is %s\n", phrase);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading