What is the equivalent to getch() & getche() in Linux?

后端 未结 6 2041
南方客
南方客 2020-11-22 05:53

I am not able to find the equivalent header file for conio.h in Linux.

Is there any option for getch() & getche() function in Linux?

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:15

    #include 
    #include 
    
    char getch(void)
    {
        char buf = 0;
        struct termios old = {0};
        fflush(stdout);
        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");
        printf("%c\n", buf);
        return buf;
     }
    

    Remove the last printf if you don't want the character to be displayed.

提交回复
热议问题