使用 editline 库

我们会用到 editline 库提供的两个函数:readlineadd_historyreadlinefgets 一样,从命令行读取一行输入,并且允许用户使用左右箭头进行编辑。add_history 可以纪录下我们之前输入过的命令,并使用上下箭头来获取。新的程序如下所示:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <editline/readline.h>
  4. #include <editline/history.h>
  5. int main(int argc, char** argv) {
  6. /* Print Version and Exit Information */
  7. puts("Lispy Version 0.0.0.0.1");
  8. puts("Press Ctrl+c to Exit\n");
  9. /* In a never ending loop */
  10. while (1) {
  11. /* Output our prompt and get input */
  12. char* input = readline("lispy> ");
  13. /* Add input to history */
  14. add_history(input);
  15. /* Echo input back to user */
  16. printf("No you're a %s\n", input);
  17. /* Free retrieved input */
  18. free(input);
  19. }
  20. return 0;
  21. }

我们增加了一些新的头文件。<stdlib.h> 提供了 free 函数。<editline/readline.h><editline/history.h> 提供了 editline 库中的 readlineadd_history 函数。

在上面的程序中,我们使用 readline 读取用户输入,使用 add_history 将该输入添加到历史纪录当中,最后使用 printf 将其加工并打印出来。

fgets 不同的是,readline 并不在结尾添加换行符。所以我们在 printf 函数中添加了一个换行符。另外,我们还需要使用 free 函数手动释放 readline 函数返回给我们的缓冲区 input。这是因为 readline 不同于 fgets 函数,后者使用已经存在的空间,而前者会申请一块新的内存,所以需要手动释放。内存的申请与释放问题我们会在后面的章节中深入讨论。