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

【CPP】自己实现一个CPP小工具demo,可以扩展其他选项

自己写CPP脚本小工具

  • 1. 思路描述
  • 2. 代码实现
    • 2.1 代码文件CppTool.cpp
    • 2.2 CMakeLists.txt
  • 3. 工具示例
    • 3.1 帮助信息
    • 3.2 工具用法
    • 3.3 实际使用


1. 思路描述

实现一个简单的命令行工具。内容包括:

  1. 命令帮助信息
  2. 参数检查,参数解析等功能。
  3. 执行其他命令。
  4. 将指令封装成一个类,在main()中调用类的对象,执行命令。

2. 代码实现

2.1 代码文件CppTool.cpp

#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <stdexcept>class CommandLineTool {
public:CommandLineTool(int argc, char* argv[]) {parseArguments(argc, argv);}void execute() {if (showHelp) {displayHelp();return;}if (showVersion) {displayVersion();return;}if (showTime) {displayCurrentTime();return;}if (!commandToExecute.empty()) {executeCommand();return;}// throw std::runtime_error("No valid command specified. Use -h for help.");}private:bool showHelp = false;bool showVersion = false;bool showTime = false;std::string commandToExecute;std::string outputFile;void parseArguments(int argc, char* argv[]) {if (argc < 2) {// throw std::runtime_error("No arguments provided. Use -h for help.");displayHelp();}std::vector<std::string> args(argv + 1, argv + argc);for (auto it = args.begin(); it != args.end(); ++it) {if (*it == "-h" || *it == "--help") {showHelp = true;} else if (*it == "-v" || *it == "--version") {showVersion = true;} else if (*it == "-t" || *it == "--time") {showTime = true;} else if (*it == "-e" || *it == "--execute") {if (++it == args.end()) {throw std::runtime_error("Missing command for -e/--execute");}commandToExecute = *it;} else if (*it == "-o" || *it == "--output") {if (++it == args.end()) {throw std::runtime_error("Missing filename for -o/--output");}outputFile = *it;} else {throw std::runtime_error("Unknown argument: " + *it);}}}void displayHelp() {std::cout << "Command Line Tool v1.0\n"<< "Usage: cltool [OPTIONS]\n\n"<< "Options:\n"<< "  -h, --help\t\tShow this help message\n"<< "  -v, --version\t\tDisplay version information\n"<< "  -t, --time\t\tDisplay current date and time\n"<< "  -e, --execute CMD\tExecute specified command\n"<< "  -o, --output FILE\tSave output to specified file\n";}void displayVersion() {std::cout << "Command Line Tool Version 1.0\n";}void displayCurrentTime() {std::time_t now = std::time(nullptr);std::tm* timeinfo = std::localtime(&now);std::cout << "Current time: "<< std::put_time(timeinfo, "%Y-%m-%d %H:%M:%S")<< std::endl;}void executeCommand() {std::cout << "Executing command: " << commandToExecute << "\n";// 实际执行命令的代码system(commandToExecute.c_str());// 示例输出std::cout << "Command executed successfully\n";if (!outputFile.empty()) {std::cout << "Output saved to: " << outputFile << "\n";// 实际保存到文件的代码}}
};int main(int argc, char* argv[]) {try {CommandLineTool tool(argc, argv);tool.execute();} catch (const std::exception& e) {std::cerr << "Error: " << e.what() << std::endl;return 1;}return 0;
}

2.2 CMakeLists.txt

cmake_minimum_required(VERSION 3.15)
project(CppTool)set(CMAKE_CXX_STANDARD 11)add_executable(CppTool CppTool.cpp)
  1. 此处默认读者会使用Cmake编译Cpp文件,如未安装Cmake工具,请参考网上其他教程安装Cmake工具,并添加环境变量。

  2. 编译命令如下:

  • 在CMakeLists.txt文件所在目录,新建下级目录build,用于存放临时文件及编译产物。依次按步骤执行下列命令:
mkdir build
cd build
cmake ..
make

3. 工具示例

3.1 帮助信息

Command Line Tool v1.0
Usage: cltool [OPTIONS]Options:-h, --help            Show this help message-v, --version         Display version information-t, --time            Display current date and time-e, --execute CMD     Execute specified command-o, --output FILE     Save output to specified file

3.2 工具用法

# 显示帮助
./CppTool -h# 显示版本
./CppTool --version# 显示当前时间
./CppTool -t# 执行命令
./CppTool -e "ls -l"# 保存输出到文件
./CppTool -t -o time.txt

3.3 实际使用

C:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>CppTool.exe
Error: No arguments provided. Use -h for help.C:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>CppTool.exe --help
Command Line Tool v1.0
Usage: cltool [OPTIONS]Options:-h, --help            Show this help message-v, --version         Display version information-t, --time            Display current date and time-e, --execute CMD     Execute specified command-i, --ipinfo          Display network IP information-o, --output FILE     Save output to specified fileC:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>CppTool.exe -t
Current time: 2025-08-16 19:45:09C:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>CppTool.exe -e "ipconfig"
Executing command: ipconfigWindows IP 配置以太网适配器 以太网 2:媒体状态  . . . . . . . . . . . . : 媒体已断开连接连接特定的 DNS 后缀 . . . . . . . :以太网适配器 以太网 3:连接特定的 DNS 后缀 . . . . . . . :本地链接 IPv6 地址. . . . . . . . : fe80::c863:71e5:c8fd:a135%12IPv4 地址 . . . . . . . . . . . . : 192.168.112.98子网掩码  . . . . . . . . . . . . : 255.255.254.0默认网关. . . . . . . . . . . . . : 192.168.112.1无线局域网适配器 WLAN:媒体状态  . . . . . . . . . . . . : 媒体已断开连接连接特定的 DNS 后缀 . . . . . . . :无线局域网适配器 本地连接* 3:媒体状态  . . . . . . . . . . . . : 媒体已断开连接连接特定的 DNS 后缀 . . . . . . . :无线局域网适配器 本地连接* 12:媒体状态  . . . . . . . . . . . . : 媒体已断开连接连接特定的 DNS 后缀 . . . . . . . :以太网适配器 蓝牙网络连接:媒体状态  . . . . . . . . . . . . : 媒体已断开连接连接特定的 DNS 后缀 . . . . . . . :
Command executed successfullyC:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>
C:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>CppTool.exe -e "date /T"
Executing command: date /T
2025/08/16 周六
Command executed successfullyC:\Users\xxx\CLionProjects\hello0614\cmake-build-debug>
http://www.dtcms.com/a/334671.html

相关文章:

  • homebrew 2
  • pytorch例子计算两张图相似度
  • 创建maven module中的override
  • Maven下载和配置-IDEA使用
  • 自动化测试的下一站:AI缺陷检测工具如何实现“bug提前预警”?
  • uniapp跨端适配方案
  • Qt 动态属性(Dynamic Property)详解
  • SDN安全开发环境中常见的框架,工具,第三方库,mininet常见指令介绍
  • 【基础-判断】HarmonyOS提供了基础的应用加固安全能力,包括混淆、加密和代码签名能力
  • 守护品质安全,防伪溯源系统打造全链路信任体系
  • 物联网 (IoT) 的顶级硬件平台
  • IEEEtaes.cls解析
  • python---模块
  • 防御保护15
  • YOLOv8环境配置命令
  • GCN图卷积神经网络的Pytorch实现
  • Azure AI Search 探索总结
  • 数据库索引视角:对比二叉树到红黑树再到B树
  • 【计算机视觉与深度学习实战】03基于Canny、Sobel和Laplacian算子的边缘检测系统设计与实现
  • DeepSeek-R1-深度解析-通过强化学习激励大语言模型的推理能力
  • Spring AI 玩转工具调用:模型帮你精确设闹钟
  • 九尾狐未来机械锂晶核
  • 盲盒抽谷机小程序系统开发:从0到1的完整方法论
  • 《从入门到精通:Kafka核心原理全解析》
  • 医院管理中的PythonAI编程:资源调配、质量监控、成本控制、医保监管与科研转化
  • 程序设计|C语言教学——C语言基础2:计算与控制语句
  • 登录与登录校验:Web安全核心解析
  • 【AndroidStudio修改中文设置】
  • 宋红康 JVM 笔记 Day03|内存结构概述、类加载器与类的加载过程、类加载器分类
  • java基础(九)sql