Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux getopt 函數用法完整整理

最近做 cache lab 用到 getopt,順手 man 3 getopt 查了一下,做個整理。

功能

getopt 用來解析命令列參數。以「-」或「--」開頭的參數視為選項元素,去掉前綴之後的字元就是選項字元。若重複呼叫 getopt,它會依序回傳每個選項元素中的選項字元。

標頭檔

#include <unistd.h>
#include <getopt.h>

相關全域變數

optind:int 型,指示下一個要解析的參數位置,初始值為 1。

optarg:char *,指向必須帶參數的選項元素的參數,例如 -nxzz 中的 "xzz"。

opterr:int 型,設為 0 則不印出錯誤訊息。

函數原型

int getopt(int argc, char * const argv[], const char *optstring);

前兩個參數與 main 相同,argc 是參數個數,argv[] 是參數陣列;optstring 由你定義的選項字元組成,例如 "abc" 表示有三個選項 -a、-b、-c。選項字元後接一個冒號代表該選項必須帶參數,且參數會存進 optarg,例如 "n:t" 表示 -n 要接參數、-t 不接;若接兩個冒號則是可有可無的可選參數,但這種可選參數不會存進 optarg。

回傳值

若當前參數是選項元素,且該選項字元存在於 optstring 中,就回傳該字元;若不在其中,回傳 '?'。每處理完一個,optind 會前移指向 argv 的下一個參數。若當前參數不是選項元素,optind 會持續偏移直到找到第一個選項元素;找不到就代表解析結束,回傳 -1。

範例

#include <unistd.h>
#include <getopt.h>

int main(int argc, char * const argv[])
{
    int opt;
    while ((opt = getopt(argc, argv, "nb:o::t")) != -1) {
        printf("opt = %c, optarg = %s, optind = %d, argv[%d] = %s\n",
               opt, optarg, optind, optind, argv[optind]);
    }
    return 0;
}
Copyright © Linux教程網 All Rights Reserved