readline库:readline-7.0.tar.gz
依赖库:ncurses-6.0.tar.gz
分别编译安装上面两个库后,便可以进行代码编译了。
测试代码:
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
static const char * cmd_list[]={
"wang",
"wanghaoije",
"deng",
"jiayi"
};
static char * cmd_gen_fn(const char * text,int state){
if(!state){
int nlen=strlen(text);
for(int i=0;i<sizeof(cmd_list)/sizeof(char*);++i){
if(!strncmp(cmd_list[i],text,nlen))
return strdup(cmd_list[i]);
}
}
return NULL;
}
static char ** cmd_complete(const char * text,int start,int end){
if(!start)
return rl_completion_matches(text,cmd_gen_fn);
else
return (char**)NULL;
}
static char ** cmd_complete2(const char * text,int start,int end){
if(!start)
{
int rn = 0;
int n = sizeof(cmd_list)/sizeof(char*);
char ** rr = new char*[n+1];
int nlen=strlen(text);
for(int i=0;i<n;++i){
rr[i]=NULL;
if(!strncmp(cmd_list[i],text,nlen))
rr[rn++] = strdup(cmd_list[i]);
}
rr[rn]=NULL;
if(!rn) {
delete[] rr;
return NULL;
}
else
return rr;
}
else{
return NULL;
}
}
int main(int argc,char * args[]){
char *p1,pn[100];
//rl_bind_key('\t',rl_complete);//系统命令补全
//rl_attempted_completion_function = cmd_complete; //自定义补全
rl_attempted_completion_function = cmd_complete2;//自定义补全
for(int i=0;i<10;++i){
p1 =readline("$");
if(!p1) break;
if(p1){
char *p =p1+strlen(p1)-1;
while(p >=p1 && (*p==10 || *p==13))
*p-- = 0;
printf("%i:%s\n",i,p1);
printf("----------\n");
add_history(p1); //这里没影响??
free(p1);
p1 = NULL;
}
}
printf("over\n");
return 0;
}
编译:
g++ nt.cpp -lreadline -lncurses -o nt