linux終端下實現的conio.h中的getch()功能函式

Koma_Wong發表於2018-09-15

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>

char getch_from_terminal()
{
	FILE *input;
    FILE *output;
    struct termios initial_settings, new_settings;
    int inputString;

    input = fopen("/dev/tty", "r");
    output = fopen("/dev/tty", "w");
    if(!input || !output)
    {
        fprintf(stderr, "Unable to open /dev/tty\n");
        exit(1);
    }

    tcgetattr(fileno(input), &initial_settings);
    new_settings = initial_settings;
    new_settings.c_lflag &= ~ICANON;
    new_settings.c_lflag &= ~ECHO;
    new_settings.c_cc[VMIN] = 1;
    new_settings.c_cc[VTIME] = 0;
    new_settings.c_lflag &= ~ISIG;

    if(tcsetattr(fileno(input), TCSANOW, &new_settings) != 0)
    {
        fprintf(stderr, "Could not set attributes\n");
    }

    while(inputString != 'q')
    {
        do
        {
            inputString = fgetc(input);
        }while(inputString == '\n' || inputString == '\r');
        return (char )inputString;
    }

    tcsetattr(fileno(input), TCSANOW, &initial_settings);
}

轉自:https://blog.csdn.net/Timsley/article/details/51424068

相關文章