c - 使用C语言在自定义shell中进行箭头键控制

标签 c shell getchar arrow-keys

我正在尝试使箭头键在单行中的字符之间(左+右)以及自定义 shell(学期项目)的历史命令之间(上+下)移动。

此时,当点击其中一个箭头 ^[[A、^[[B、^[[C 或 ^[[D] 时,会显示出来,在按下 Enter 后,我发现其中一个箭头被按下:

char a = getchar();

if (a == '\033') {
    getchar();
    int ch2 = getchar();
    switch(ch2){
        case 'A': 
            printf("UP\n"); 
            break;
        case 'B': 
            printf("DOWN\n"); 
            break;
        case 'D': 
            printf("LEFT\n"); 
            break;
        case 'C': 
            printf("RIGHT\n"); 
            break;
        default:
            printf("SOME OTHER SCROLL KEY PRESSED: %d %d\n", a, ch2); 
            break;
    }
}

我想要得到的是,只要我击中其中一个箭头,就会发生操作而不显示任何内容。

最佳答案

默认情况下,unix 系统中的终端输入是行缓冲的,您可以使用 termios 为 stdin 函数指定自己的返回条件:

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

static struct termios orig_termios;

char get_char_wait_for_keypress(void) {
    struct termios raw;
    // Get stdin file descriptor (0 by default)
    int stdin_fileno = fileno(stdin);
    // Copy terminal io settings
    raw = orig_termios;
    // Set return condition at first byte being received (For input timeout you can use `raw.c_cc[VTIME] = secs`)
    raw.c_cc[VMIN] = 1;
    // Apply settings with new return condition
    tcsetattr(stdin_fileno, TCSANOW, &raw);
    // Get char with new conditions
    char c = getchar();
    // Restore old settings
    tcsetattr(stdin_fileno, TCSANOW, &orig_termios);
    return c;
}

int main(void) {
struct termios raw;
    char c = get_char_wait_for_keypress();
    printf("%d", c);
}

关于c - 使用C语言在自定义shell中进行箭头键控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380560/

相关文章:

c - EOF 宏如何与 getchar 一起使用?

c - C 程序中内联的第二次倒计时

c - 使用通用函数指针

bash - 如何使用 Bash 脚本中的密码运行 sftp 命令?

bash - 将 EC2 用户数据 shell 脚本存储在私有(private) S3 存储桶中是否安全?

c - 如何从 C 中的父进程分离 fork 进程

C在while循环中读取输入

C++ : Fastest way to read string from stdin

c - 海合会表现

arrays - 删除小于数组左侧元素的元素