当前位置: 首页 > news >正文

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

效果:

在这里插入图片描述

http://www.xdnf.cn/news/690859.html

相关文章:

  • 运用集合知识做斗地主案例
  • 智能指针的使用及原理
  • MCP 登场:掘金开启 AI 前端项目部署新时代
  • 第三章、数据链路层
  • C++智能指针用法及内存管理
  • 双因子COX 交互 共线性 -spss
  • 多态 向上转型
  • YOLO人体姿态估计Pytorch推理ONNX模型推理
  • Android-GestureDetector学习总结
  • 微信小程序(uniapp)对接腾讯云IM
  • Vue 实例生命周期
  • 2025.5.28总结
  • 接口幂等性原理与方案总结
  • Avue表单个别字段实现全选的思路
  • 【Pandas】pandas DataFrame drop
  • Transformer核心技术解析LCPO方法:精准控制推理长度的新突破
  • Redis学习(十四)主从复制的工作原理、集群搭建(一主二从)
  • Android 云手机横屏模式下真机键盘遮挡输入框问题处理
  • [AD] Noxious LLMNR+DHCP+NTLMv2+Kerberos+SMB
  • 高精度导航 | RTK:2025年高精度导航算法综述,包括:原理,数据,公式,完整代码,开源代码链接
  • 网络协议之办公室网络是怎样的?
  • Mac M1编译OpenCV获取libopencv_java490.dylib文件
  • xcode 旧版本、历史版本下载
  • 【C/C++】高性能网络编程之Reactor模型
  • 网站缓存入门与实战:浏览器与Nginx/Apache服务器端缓存,让网站速度起飞!(2025)
  • git配置(1): 根据remote自动选择账号执行commit
  • MCU - SPI总线介绍 + W25Qx驱动设计
  • node-DeepResearch开源ai程序用于深入调查查询,继续搜索、阅读网页、推理,直到找到答案
  • SpringBoot项目快速打包与部署,War包⽅式打包部署与Jar包⽅式打包部署两种方式
  • 迁移学习模型构建指南(Python实现)