c - 在 get_line 实现中,如何允许用户移动光标?

标签 c shell getline stdio

所以,我目前正在开发一个小型 shell。
我使用自己的 getline 实现获取用户输入,该实现反复调用 fgetc(stdin) 并重新分配以读取一行。

如何允许用户使用左右键在他当前正在书写的输入中移动光标?

函数:

#define LINE_BUFSIZE 256
static char *get_line(void)
{
    char  *line   = malloc(LINE_BUFSIZE);
    char  *linep  = line;
    size_t lenmax = LINE_BUFSIZE;
    size_t len    = lenmax;
    int    c;

    if (!line)
        return NULL;

    for (;;) {
        c = fgetc(stdin);
        if (c == EOF)
            break;

        if (--len == 0) {
            len = lenmax;
            lenmax *= 3;
            lenmax /= 2;
            char *linen = realloc(linep, lenmax);

            if (!linen) {
                free(linep);
                return NULL;
            }

            line  = linen + (line - linep);
            linep = linen;
        }

        if ((*line++ = c) == '\n')
            break;
    }
    *line = '\0';
    return linep;
}

最佳答案

基本上有三种方法可以做到这一点。按工作量递减顺序:

  1. 将终端置于原始模式以便能够接收 Ctrl-B 等字符,然后处理它们。这真的是在重新发明轮子,除非你愿意花很多时间白做(除非是为了学习),否则不要去那里。
  2. 由于这个问题已经被解决了一百多次,而且许多程序都需要它,所以开发了一个名为 termcap 的库来抽象终端功能。如果您希望您的程序不仅可以在 xterm 中运行,而且还可以在其他终端上运行,这是可行的方法。
  3. 使用 GNU readline 库。从它的手册:

    #include <stdio.h>
    #include <readline/readline.h>
    #include <readline/history.h>
    
    char *
    readline (const char *prompt);
    

DESCRIPTION

readline will read a line from the terminal and return it, using prompt as a prompt. If prompt is NULL or the empty string, no prompt is issued. The line returned is allocated with malloc(3); the caller must free it when finished. The line returned has the final newline removed, so only the text of the line remains.

readline offers editing capabilities while the user is entering the line. By default, the line editing commands are similar to those of emacs. A vi-style line editing interface is also available.

关于c - 在 get_line 实现中,如何允许用户移动光标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49617687/

相关文章:

c - 在结构体中声明结构体

linux - 通过 Shell 脚本确定 Linux 进程是否正在使用给定参数运行

c++ - 使用getline连续输入行到txt文档的结尾C++

linux - bash 隐藏默认的 stderr 代码并将其替换为我自己的

shell - 在 awk 中按特定顺序打印文件

CONTROL\crashes 调用 getline

c++ - getline 和 16h (26d) 字符

c - lroundf()、floor() 和 nearbyintf() 有什么区别?

c - 为什么我在 C 中收到参数初始化错误?

c - 遍历可能的密码时无限循环