HOWTO · C++
在 C++ 中使用 getopt 處理引數
本文演示瞭如何在 C++ 中使用 getopt() 函式來處理引數。
本文演示瞭如何使用 getopt() 函式來處理命令列中傳遞給程式碼的引數。本教程還解釋瞭如何操作程式碼以執行特定輸入的某些操作。
在 C++ 中使用 getopt() 函式處理引數
假設我們有如下所示的程式碼。
// File titled arg_test.cpp
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int opt;
while ((opt = getopt(argc, argv, ":f:asd")) != -1) {
if (opt == 'a' || opt == 's' || opt == 'd') {
printf("Option Selected is: %c\n", opt);
} else if (opt == 'f') {
printf("Filename entered is: %s\n", optarg);
} else if (opt == ':') {
printf("Option requires a value \n");
} else if (opt == '?') {
printf("Unknown option: %c\n", optopt);
}
}
// optind is for the extra arguments that are not parsed by the program
for (; optind < argc; optind++) {
printf("Extra arguments, not parsed: %s\n", argv[optind]);
}
return 0;
}
getopt() 函式的語法如下:
getopt(int argc, char *const argv[], const char *optstring)
argc 是一個整數,argv 是一個字元陣列。optstring 是一個字元列表,每個字元代表一個單個字元長的選項。
該函式在處理完輸入中的所有內容後返回 -1。
getopt() 函式在遇到它不認識的東西時返回 ?。此外,這個無法識別的選項儲存在外部變數 optopt 中。
預設情況下,如果選項需要一個值,例如,在我們的例子中,選項 f 需要一個輸入值,所以 getopt() 將返回 ?。但是,通過將冒號 (:) 作為 optstring 的第一個字元,該函式返回: 而不是 ?。
在我們的例子中,輸入 a、s 或 d 應該返回選項本身,使用 f 應該返回作為引數提供的檔名,其他所有內容都不應被視為有效選項。
要執行上述程式碼,你可以在終端中使用類似的命令:
gcc arg_test.cpp && ./a.out
當然,僅僅輸入這個不會給你任何有用的輸出。我們將輸入一個示例用例和一個示例輸出,並解釋如何處理每個命令。
如果我們輸入以下命令作為示例:
gcc arg_test.cpp && ./a.out -f filename.txt -i -y -a -d testingstring not_an_option
我們將得到以下輸出:
Filename entered is: filename.txt
Unknown option: i
Unknown option: y
Option Selected is: a
Option Selected is: d
Extra arguments, not parsed: testingstring
Extra arguments, not parsed: not_an_option
選項 a 和 d 按預期返回。f 標誌後給出的檔名也被報告,選項 i 和 y 進入 ? 類別並被識別為未知命令。
在這裡,我們可以看到除了上述場景之外,我們在 getopt() 函式之後新增的最後一個迴圈處理了該函式未處理的剩餘引數(testingstring 和 not_an_option,在我們的例子中)。