Unix下如何直接获取键盘输入而不需要以回车作为结束符的方法总结

来源:互联网 发布:洛奇英雄传au优化 编辑:程序博客网 时间:2024/06/10 03:56

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <curses.h>

//sttyコマンドは標準出力で使用される端末の設定と確認を行うことができます。
//コマンドリファレンスはこちらを参考に。
//http://www.linux.or.jp/JM/html/GNU_sh-utils/man1/stty.1.html


int keyInput1()
{
    char ab_Chr[250];
    int gi_Tty;
        /* 端末を入力モードでオープン */
    if((gi_Tty = open("/dev/tty",O_RDONLY)) == -1)/* 異常時 */{
        /* 異常で復帰 */
        return -1;
    }
    system("stty raw -echo");
   
    read(gi_Tty, ab_Chr, 1);
    close(gi_Tty);
    system("stty -raw echo");
    printf("%c/n",ab_Chr[0]);
    return ab_Chr[0];
}

int keyInput2()
{
    char ab_Chr[250];
    char c;
/*
 *ioctl() would be better here; only lazy 
 *programmers do it this way: 
*/

    system("/bin/stty raw");
    c=getchar();
    system("/bin/stty -raw");
    return c;
}

//terminalの属性を修正する
int keyInput3()
{

    int c;
    struct termios new_settings;
    struct termios stored_settings;
    tcgetattr(0,&stored_settings);
    new_settings = stored_settings;
    new_settings.c_lflag &= (~ICANON);
    new_settings.c_cc[VTIME] = 0;
    new_settings.c_cc[VMIN] = 1;
    tcsetattr(0,TCSANOW,&new_settings);
    c = getchar();
    tcsetattr(0,TCSANOW,&stored_settings);

    return c;
}


//curscrライブラリで実現する
int keyInput4()
{

    WINDOW  *curscr, *stdscr;
    unsigned char c,b,a,buf[32];

    stdscr = initscr();
    //clear();
    c=getch();
    printw("/n"); 
    //printw("c= %c/n",c);
    refresh();
    endwin();
   
    return c;
}

 

int main()
{
    char t_ReadBuf[250];
   
    while(1)
    {
        int c ;
        printf("Call keyInput1/n");
        c=keyInput1();
        printf("Input c=%c/n",c);
       
        printf("/n");
       
        printf("Call keyInput2/n");
        c=keyInput2();
        printf("/nInput c=%c/n",c);

        printf("/n");

        printf("Call keyInput3/n");
        c=keyInput3();
        printf("/nInput c=%c/n",c);
                               
        printf("Call keyInput4/n");
        c=keyInput4();
        printf("/nInput c=%c/n",c);
       
        if (c == 'q')
        {
            return 0;
        }
    }

}

//cc KeyInput.c -l curses