C语言使用readline库实现带tab补全命令的shell终端
例程:
#include <readline/history.h>
#include <readline/readline.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *commands[] = {"cd", "cda", "cdc", "cddd", NULL};
char *command_generator(const char *text, int state)
{
static int index, len;
char *name;
if (!state)
{
index = 0;
len = strlen(text);
}
while (name = commands[index])
{
index++;
if (strncmp(name, text, len) == 0)
return (strdup(name));
}
return ((char *)NULL);
}
char **my_completion(const char *text, int start, int end)
{
char **matches;
matches = (char **)NULL;
if (start == 0)
matches = rl_completion_matches(text, command_generator);
return (matches);
}
void initialize_readline()
{
chdir("/workdir");
rl_readline_name = ">";
rl_attempted_completion_function = my_completion;
}
int main(int argc, char **argv)
{
char *line, *s;
initialize_readline();
for (;;)
{
line = readline("aaa@xxx:~$ ");
if (!line)
break;
add_history(line);
free(line);
}
exit(0);
}