readline

来源:互联网 发布:如何评价詹姆斯知乎 编辑:程序博客网 时间:2024/05/16 12:50

readline库是在linux命令行里面输入和程序解析输入的最好用的库,下面是它的使用示例,其中加入了历史条目检索调用

#include <stdio.h>

#include <stdlib.h>

#include <readline/readline.h>

 

int main(int argc, char **argv)

{

 char*buf = NULL;

 

 while (1) {

 buf= readline(">");

 if(buf != NULL) {

 printf("get: %s\n", buf);

 add_history(buf);

 

 if(strcmp(buf, "quit") == 0){

 free(buf);

 break;

 }else

 free(buf);

 }  

 }  

 

 return 0;

}

 

编译时别忘了加上-lreadline选项。

 

 

 

 

 

使用此库函数可以在输入时可以有像shell那样的快捷键功能,例如命令回放等;不过在编译的时候要加入-lreadline选项来链接它的函数库。

 下面一个例子来看看:

 #include <stdio.h>

 #include <readline/readline.h>

 #include <readline/history.h>

 

 static char *line_read = (char *)NULL;

 

 char*rl_gets()

 {

 if(line_read)

 {      free (line_read);

 line_read = (char *)NULL;

 }

 line_read = readline("Please Enter:");

 

 if(line_read && *line_read)

 add_history(line_read);

 return(line_read);

 }

 

 intmain()

 {char *mline;

 mline = rl_gets();

 printf("%s\n",mline);

 }

 看看我们自己实现的rl_gets函数,有了意外的收获,opensuse10.3konsole有个bug,就是自己写的程序无法实现输入中文,现在用了readline之后就好可以了。

 ------------------

 custom fuctions:

 可以定制readline的快捷键功能:

 使用函数:int rl_bind_key(int key,rl_commond_func_t *function);

 例如:rl_bind_key('\t', rl_insert);可以将TAB键定制为输入一个tab.

 

tiswww.case.edu/php/chet/readline/readline.html#SEC23

 

 ------------------------------------------------------

 近期学习李老大的shell模式,感觉readline的那个命令补全功能很强大,举个例子先

 static char* command_generator(const char*text, int state)

 {

 const char *name;

 static int list_index, len;

 

 if(!state)

 {

 list_index = 0;

 len= strlen (text);

 }

 

 while (name = commands[list_index])

 {

 list_index++;

 

 if(strncmp (name, text, len) == 0)

 return strdup(name);

 }

 

 return ((char *)NULL);

 }

 

 char** command_completion (const char *text,int start, int end)

 {

 char**matches = NULL;

 

 if(start == 0)

 matches = rl_completion_matches (text,command_generator);

 

 return (matches);

 }

 上面是我们要自己定义的回调函数其中的commands[]为一个字符串数组,存放我们自己定义的命令。

 最后来个初始化函数:

 voidinitialize_readline ()

 {

 rl_readline_name = "jdbshell";

 rl_attempted_completion_function =command_completion;

 

 return ;

 }

 此时使用readline(">>")就添加了自动补全了,没事按TabOK了。

原创粉丝点击