Read from Stdin without Writing to the Console





12
Date Submitted Thu. Oct. 12th, 2006 5:34 PM
Revision 1 of 1
Scripter wiz1705
Tags C | stdin | termios
Comments 0 comments
Using the Termios library, we can have the user enter a character on the keyboard, without it being displayed on the screen.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>
#include <memory.h>

int mygetch()
{
        struct termios oldt, newt;

        int ch;
        tcgetattr(STDIN_FILENO, &oldt);
        newt = oldt;
        newt.c_lflag &= ~(ICANON | ECHO);
        tcsetattr(STDIN_FILENO, TCSANOW, &newt);
        ch = getchar();
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

        return ch;
}

int main(int argc, char *argv[])
{
        char answer;

        while (answer == 'Y' || answer == 'y') {
                printf("Continue? [Y/N] ");
                answer = mygetch();
        }

        printf("Exiting...\n");

        return 0;
}

Zachary Howe

autoignition.net

Comments

There are currently no comments for this snippet.

Voting