c语言实现Linux命令行补全机制
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>// 自动补全命令列表
const char *commands[] = {"start", "stop", "restart", "status", "help", "configure", "update", "exit", NULL
};// 循环查找对应命令函数
char *command_generator(const char *text, int state) {static int list_index, text_len;if (!state) {list_index = 0;text_len = strlen(text);}while (commands[list_index]) {if (strncmp(commands[list_index], text, text_len) == 0)return strdup(commands[list_index++]);list_index++;}return NULL;
}// readline绑定函数,Tab键会调用此函数
char **my_completion(const char *text, int start, int end) {return rl_completion_matches(text, command_generator);
}int main() {// 初始化 Readline 设置rl_attempted_completion_function = my_completion; // 注册补全函数rl_attempted_completion_over = 1; // 禁止默认补全行为using_history(); // 启用历史记录while (1) {char *input = readline("Narnat> ");if (!input) break; // EOF 退出if (*input) {add_history(input); // 添加到历史记录printf("执行命令: %s\n", input);}free(input);}return 0;
}
核心在于使用Tab按键后会自动调用readline提供的接口函数rl_attempted_completion_function,将此接口函数实现完毕后即可遍历自己设置的命令,将符合的命令回显出来
当用上下按键的时候会调用到history函数中储存的历史命令,将之前用过的命令显示出来
编译:
gcc -o main main.c -lreadline -lncurses
效果: