【问题标题】:readline() internal bufferreadline() 内部缓冲区
【发布时间】:2014-12-26 17:20:16
【问题描述】:

使用GNU Readline:

函数readline() 显示提示并读取用户输入。

我可以修改它的内部缓冲区吗?以及如何实现?

#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char* input;
        // Display prompt and read input 
        input = readline("please enter your name: ");

        // Check for EOF.
        if (!input)
            break;

        // Add input to history.
        add_history(input);

        // Do stuff...

        // Free input.
        free(input);
    }
}

【问题讨论】:

  • 它的“内部缓冲区”是什么?也许它没有一个?我真的不明白你想要达到什么目的。
  • 使用标准std::cin,我们可以使用rdbuf()函数访问其内部缓冲区。不知道使用readline()时是否可以@
  • 请先查看有关Command line editing的文档。
  • 请从您的标题中删除“C++”,您的问题中没有特定于 C++ 的内容!

标签: c linux gnu libreadline


【解决方案1】:

是的,可以修改 readline 的编辑缓冲区,例如通过使用函数rl_insert_text()。为了使它有用,我认为你需要使用 readline 稍微复杂一点的“回调接口”,而不是在你的例子中全唱和跳舞的readline() 函数。

Readline 附带了非常好的和完整的documentation,因此我只提供一个最小的示例程序来帮助您入门:

/* compile with gcc -o test <this program>.c -lreadline */

#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>

void line_handler(char *line) { /* This function (callback) gets called by readline
                                   whenever rl_callback_read_char sees an ENTER */ 
  printf("You changed this into: '%s'\n", line);
  exit(0);
}

int main() {
  rl_callback_handler_install("Enter a line: ", &line_handler);
  rl_insert_text("Heheheh...");    /* insert some text into readline's edit buffer... */
  rl_redisplay ();                 /* Make sure we see it ... */

  while (1) {
    rl_callback_read_char();       /* read and process one character from stdin */
  }
}    

【讨论】:

  • 是否可以在终端底部放置输入线?
  • @Kira San:Readline 没有任何“钩子”可以帮助您实现这一目标。您可以尝试使用 ncurses 来建立例如终端上的不同窗口,包括底部的输入区域,但这并不容易。有关这方面的更多信息(包括可能的出路),请参见例如invisible-island.net/ncurses/ncurses.faq.html#readline_library
  • 是的,这并不容易,这就是我选择 GNU Readline 的原因。我问了这么多问题。但是有一个函数可以取消 readline 输入请求吗?
  • 是的,但是对于评论来说答案有点太长了,而且我还没有找到关于 SO 的答案。你能提出一个新问题吗?
  • 谢谢,这是我的新问题:stackoverflow.com/questions/27661706/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2015-02-16
  • 2020-12-05
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多