简介
linenoise是一个命令行编辑库(line editing library),readline的替代品,可以用于tab自动补全方法的实现。目前linenoise已经在Redis, MongoDB,Android中使用。
这篇 blog 对linenoise 有更为详细的描述
源码路径
/redis-5.0.10/deps/linenoise
API
/**
* 从终端获取字符串
* @param prompt 要打印的提示语
*/
char *linenoise(const char *prompt) {
...
}
/**
* 清空屏幕输出
*/
void linenoiseClearScreen(void) {
if (write(STDOUT_FILENO,"\x1b[H\x1b[2J",7) <= 0) {
/* nothing to do, just to avoid warning. */
}
}
使用示例
新建一个 mytest.c
文件,输入以下内容
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <string.h>
#include "linenoise.h"
void main() {
const char * prompt = "127.0.0.1> ";
char * line;
while(line = linenoise(prompt)) {
if (strcmp(line, "exit") == 0) {
break;
}
if (strcmp(line, "clear") == 0) {
linenoiseClearScreen(); // 清空屏幕
continue;
}
printf("%s \n", line);
}
}
- 通过
while
不断的读取终端的输入,并打印。当需到exit
时,程序退出
编译与运行效果
编译程序 gcc -o mytest mytest.c linenoise.o
运行效果:
[root@xxxxxxx linenoise]# ./mytest
127.0.0.1> hehe
hehe
127.0.0.1>
127.0.0.1> xixix
xixix
127.0.0.1> hehe
hehe
127.0.0.1> exit
Redis 的使用
redis
正是通过此函数来获取用户的命令行输入
redis-cli.c
static void repl(void) {
....
// 从终端读取命令
while((line = linenoise(context ? config.prompt : "not connected> ")) != NULL) {
。。。。
/*
* 获取用户输入后的处理逻辑
*/
}
exit(0);
}