加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

readline库函数的使用

(2011-08-14 00:02:28)
标签:

杂谈

 

先看下例子
#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, int end)
{
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

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有