2

使用GNU 阅读线

该函数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);
    }
}
4

1 回答 1

5

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

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

/* 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 */
  }
}    
于 2014-12-26T17:52:53.930 回答