自己寫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>