在用 C/C++ 寫一些工具時,需要通過命令行傳一些參數,這樣就可以在命令行終端使用該工具或在腳本中使用該工具,從而實現批量處理。
比如近期需要實現一個對文件進行加解密的工具,我需要通過命令行傳遞如下參數:
- 需要處理的輸入文件;
- 處理類型:加密還是解密;
- 處理多少長度;
- 輸出文件;
1、函數說明
本文采用的短參數,函數定義如下:
#include <unistd.h> //系統頭文件
int getopt(int argc, char * const argv[], const char * optstring);
函數說明:
argc :由 main() 傳遞的參數個數
argv :由 main() 傳遞的參數內容
optstring :表示預處理的選項字符串
getopt() 該函數會返回在 argv 中與 optstring 對應的下一個選項字符。
如果找到符合的參數則返回此參數字符,
如果 optstring 中不包含輸入的參數字符則返回 ’?‘ 字符,
分析結束則返回 -1。
如果 optstring 裏的字符後帶有冒號 ":",則表示該選項還有相關的參數,可通過 optarg 獲取額外參數。
具體用法見下面代碼。
2、編碼應用
使用代碼如下:
#include <iostream>
#include <unistd.h>
using namespace std;
enum OptionType {
TYPE_UNKNOWN = 0,
TYPE_ENCRYPT,
TYPE_DECRYPT
};
/**
* 文件加解密工具,使用方法如下:
*
* ./FileEnDeCryptor -i <InputFile> -t <E/D> -n <Num> -o <OutFile>
*
* InputFile :必須參數,需要處理的輸入文件
* E/D :必須參數,操作類型:加密 E, 解密 D
* Num :可選參數,需要處理的數據長度,從文件開始位置計算,如果不設置該參數則處理整個文件
* OutFile :可選參數,處理後的輸出文件路徑,如果不設置則直接在輸入文件上操作
*/
int main(int argc, char * argv[]) {
int opt = 0;
string input_file;
string output_file;
OptionType option_type = TYPE_UNKNOWN;
int process_num = 0;
while((opt = getopt(argc, argv, "hi:t:n:o:")) != -1) {
switch(opt) {
case 'h':
printf("Usage: ./FileEnDeCryptor -i <InputFile> -t <E/D> -n <Num> -o <OutFile>\n");
return 0;
case 'i':
input_file = string(optarg);
break;
case 'o':
output_file = string(optarg);
break;
case 't':
if (!strcmp("E", optarg)) {
option_type = TYPE_ENCRYPT;
} else if (!strcmp("D", optarg)) {
option_type = TYPE_DECRYPT;
} else {
printf("Error: Option type must be E or D!\n");
return -1;
}
break;
case 'n':
process_num = atoi(optarg);
break;
}
}
// 參數檢查
if (TYPE_UNKNOWN == option_type)
{
printf("Error: Option type must be E or D!\n");
return -1;
}
if (input_file.empty()) {
printf("Error: Input file path could not be null!\n");
return -1;
}
if (output_file.empty()) {
output_file = string(input_file);
}
printf("input_file = %s, option_type = %d, process_num = %d, output_file = %s\n",
input_file.c_str(), option_type, process_num, output_file.c_str());
// TODO Use Args
return 0;
}
CMakeList.txt
cmake_minimum_required(VERSION 3.6)
project(FileEnDeCryptor)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES main.cpp)
add_executable(FileEnDeCryptor ${SOURCE_FILES})
3、工具編譯
cd source (CMakeLists.txt 所在目錄)
cmake .
make
4、測試運行
# 加密全部文件,輸入輸出爲相同文件
./FileEnDeCryptor -i 1.jpg -t E
# 解密全部文件,輸入輸出爲相同文件
./FileEnDeCryptor -i 1.jpg -t D
# 加密全部文件,並輸出到新的文件
./FileEnDeCryptor -i 1.jpg -t E -o 1_out.jpg
# 解密全部文件,並輸出到新的文件
./FileEnDeCryptor -i 1_out.jpg -t D -o 1_ok.jpg