DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Mariusz has posted 3 posts at DZone. View Full User Profile

Untill Keypressed / Conio.h

01.22.2008
| 4835 views |
  • submit to reddit
        Turbo Pascal and conio.h allowed immediate character reading, without wainting for enter. Following code does the same under unix terminals:

#include <stdio.h>
#include <termios.h>

char getch(void) {
        char buf = 0;
        struct termios old = {0};
        if (tcgetattr(0, &old) < 0)
                perror("tcsetattr()");
        old.c_lflag &= ~ICANON;
        old.c_lflag &= ~ECHO;
        old.c_cc[VMIN] = 1;
        old.c_cc[VTIME] = 0;
        if (tcsetattr(0, TCSANOW, &old) < 0)
                perror("tcsetattr ICANON");
        if (read(0, &buf, 1) < 0)
                perror ("read()");
        old.c_lflag |= ICANON;
        old.c_lflag |= ECHO;
        if (tcsetattr(0, TCSADRAIN, &old) < 0)
                perror ("tcsetattr ~ICANON");
        return (buf);
}

int main() {
        char key;
        printf("Press 'x' to exit...\n");
        while((key=getch()) && (key != 'x'))
                printf ("you pressed %c\n", key);
        return(0);
}