歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux中getopt函數用法

Linux中getopt函數用法

日期:2017/3/1 9:57:45   编辑:Linux編程

最近做cache lab 用到了getopt函數, 用man 3 getopt查看了下用法, 做個總結.

描述:getopt函數是用來解析命令行參數的, 以‘-’或‘--’開頭的參數為選項元素,除去‘-’或‘--’的選項元素為選項字符。如果getopt函數被重復調用,則它將會依次返回每個選項元素中的選項字符。

使用getopt函數需要包含以下頭文件:

#include <unistd.h>

#include <getopt.h>

有幾個全局變量與getopt函數解析參數有關:

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

optarg: char *, 必須接參數的選項元素的參數, 如上面的-nxzz, optarg 就指向"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後

不接參數,如 -n xzz -t 或 -nxzz t,有兩個冒號說明該選項可接可選參數, 但可選參數不保存在optarg中.

返回值: 如果當前處理的參數為選項元素,且該選項字符在optstring字符串中, 即為你定義的選項, 則返回該

選項字符,如果該選項字符不是你定義的, 那麼返回字符'?', 並更新全局變量optind, 指向argc數組中的下一

個參數. 如果當前處理的參數不是選項元素, 則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