【CPP】自己实现一个CPP小工具demo,可以扩展其他选项
自己写CPP脚本小工具
- 1. 思路描述
- 2. 代码实现
- 2.1 代码文件CppTool.cpp
- 2.2 CMakeLists.txt
- 3. 工具示例
- 3.1 帮助信息
- 3.2 工具用法
- 3.3 实际使用
1. 思路描述
实现一个简单的命令行工具。内容包括:
- 命令帮助信息
- 参数检查,参数解析等功能。
- 执行其他命令。
- 将指令封装成一个类,在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)
-
此处默认读者会使用Cmake编译Cpp文件,如未安装Cmake工具,请参考网上其他教程安装Cmake工具,并添加环境变量。
-
编译命令如下:
- 在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>