读取键盘输入流改为原始模式

摘自 http://github.com/antirez/linenoise

 键盘的Ctrl+A    ... Ctrl+Z    对应 ASCII的 1  ..  26

唯有Ctrl+M  不是13

13是Enter

Ctrl+I     和 Tap  都是9

27是Esc

下面来验证一下

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
// #include <stdlib.h>
// #include <stdio.h>
#include <errno.h>
// #include <string.h>
// #include <stdlib.h>
// #include <ctype.h>
// #include <dirent.h>
// #include <sys/types.h>
// #include <sys/ioctl.h>
// #include <sys/stat.h>
// #include <unistd.h>

static struct termios orig_termios; /* In order to restore at exit.*/

/* Raw mode: 1960 magic shit. */
int linenoiseEnableRawMode(int fd)
{
    struct termios raw;

    if (!isatty(STDIN_FILENO))
        goto fatal;
    // if (!atexit_registered) {
    //     atexit(linenoiseAtExit);
    //     atexit_registered = 1;
    // }
    if (tcgetattr(fd, &orig_termios) == -1)
        goto fatal;

    raw = orig_termios; /* modify the original mode */
    /* input modes: no break, no CR to NL, no parity check, no strip char,
     * no start/stop output control. */
    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
    /* output modes - disable post processing */
    raw.c_oflag &= ~(OPOST);
    /* control modes - set 8 bit chars */
    raw.c_cflag |= (CS8);
    /* local modes - choing off, canonical off, no extended functions,
     * no signal chars (^Z,^C) */
    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
    /* control chars - set return condition: min number of bytes and timer.
     * We want read to return every single byte, without timeout. */
    raw.c_cc[VMIN] = 1;
    raw.c_cc[VTIME] = 0; /* 1 byte, no timer */

    /* put terminal in raw mode after flushing */
    if (tcsetattr(fd, TCSAFLUSH, &raw) < 0)
        goto fatal;
    // ls.rawmode = 1;
    return 0;

fatal:
    errno = ENOTTY;
    return -1;
}

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

    linenoiseEnableRawMode(STDIN_FILENO);
    for (;;)
    {
        printf("请输入字符:");
        c = getchar();

        printf("输入的字符为:%d\r\n", c);
        // getchar();
    }

    return 0;
}
gcc -Wall -o test_read test_read.c

 

 

[root@localhost cmd]# ./test_read
请输入字符:输入的字符为:1
请输入字符:输入的字符为:2
请输入字符:输入的字符为:3
请输入字符:输入的字符为:4
请输入字符:输入的字符为:5
请输入字符:输入的字符为:6
请输入字符:输入的字符为:7
请输入字符:输入的字符为:8
请输入字符:输入的字符为:9
请输入字符:输入的字符为:10
请输入字符:输入的字符为:11
请输入字符:输入的字符为:12
请输入字符:输入的字符为:14
请输入字符:输入的字符为:15
请输入字符:输入的字符为:16
请输入字符:输入的字符为:17
请输入字符:输入的字符为:18
请输入字符:输入的字符为:19
请输入字符:输入的字符为:20
请输入字符:输入的字符为:21
请输入字符:输入的字符为:22
请输入字符:输入的字符为:23
请输入字符:输入的字符为:24
请输入字符:输入的字符为:25
请输入字符:输入的字符为:26

 

posted @ 2021-05-27 11:10  LiuYanYGZ  阅读(107)  评论(0编辑  收藏  举报