readline库函数使用说明

来源:互联网 发布:php 使用fileinput.js 编辑:程序博客网 时间:2024/06/06 09:42
在chinaunix中下载readline,同时下载ncurses库,因为readline can be called when ncurse lib is installed.

#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);
}

int main()
{ char *mline;
mline = rl_gets();
printf("%s\n",mline);
}
运行后就可以使用tab补全文件了。但是不能补全命令。
下面这个程序可以补全命令,
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, intend)
{
char **matches = NULL;

if (start == 0)
matches = rl_completion_matches (text, command_generator);

return (matches);
}
上面是我们要自己定义的回调函数其中的commands[]为一个字符串数组,存放我们自己定义的命令。
最后来个初始化函数:
void initialize_readline ()
{
rl_readline_name = "jdbshell";
rl_attempted_completion_function = command_completion;

return ;
}

可以定制readline的快捷键功能:
使用函数:int rl_bind_key(int key, rl_commond_func_t *function);
例如:rl_bind_key('\t', rl_insert);可以将TAB键定制为输入一个tab.

应用这个库函数,我成功的为字符界面下的飞鸽传书加上了补全的功能,包括命令和文件的补全。
编译的时候要加上两个库:readline 和 termcap