日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux 之 getopt_long()

發(fā)布時間:2023/12/15 linux 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux 之 getopt_long() 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文件

#include <getopt.h>

函數(shù)原型

int getopt_long(int argc, char * const argv[], const char *optstring, const struct option *longopts, int *longindex);

函數(shù)說明

getopt被用來解析命令行選項參數(shù)。 getopt_long支持長選項的命令行解析,使用man getopt_long,得到其聲明如下: int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex); 函數(shù)中的argc和argv通常直接從main()的兩個 參數(shù)傳遞而來。optsting是選項參數(shù)組成的字符串: 字符串optstring可以下列元素: 1.單個字符,表示選項, 2.單個字符后接一個冒號:表示該選項后必須跟一個參數(shù)。參數(shù)緊跟在選項后或者以空格隔開。該參數(shù)的指針賦給optarg。 3 單個字符后跟兩個冒號,表示該選項后可以有參數(shù)也可以沒有參數(shù)。如果有參數(shù),參數(shù)必須緊跟在選項后不能以空格隔開。該參數(shù)的指針賦給optarg。(這個特性是GNU的擴張)。 optstring是一個字符串,表示可以接受的參數(shù)。例如,"a:b:cd",表示可以接受的參數(shù)是a,b,c,d,其中,a和b參數(shù)后面跟有更多的參數(shù)值。(例如:-a host -b name) 參數(shù)longopts,其實是一個結(jié)構(gòu)的實例: struct option { const char *name; //name表示的是長參數(shù)名 int has_arg; //has_arg有3個值,no_argument(或者是0),表示該參數(shù)后面不跟參數(shù)值 // required_argument(或者是1),表示該參數(shù)后面一定要跟個參數(shù)值 // optional_argument(或者是2),表示該參數(shù)后面可以跟,也可以不跟參數(shù)值 int *flag; //用來決定,getopt_long()的返回值到底是什么。如果flag是null,則函數(shù)會返回與該項option匹配的val值 int val; //和flag聯(lián)合決定返回值 } 給個例子: struct option long_options[] = { {"a123", required_argument, 0, 'a'}, {"c123", no_argument, 0, 'c'}, } 現(xiàn)在,如果命令行的參數(shù)是-a 123,那么調(diào)用getopt_long()將返回字符'a',并且將字符串123由optarg返回(注意注意!字符串123由optarg帶回!optarg不需要定義,在getopt.h中已經(jīng)有定義),那么,如果命令行參數(shù)是-c,那么調(diào)用getopt_long()將返回字符'c',而此時,optarg是null。最后,當getopt_long()將命令行所有參數(shù)全部解析完成后,返回-1。

范例

#include <stdio.h> #include <getopt.h> char *l_opt_arg; char* const short_options = "nbl:"; struct option long_options[] = { { "name", 0, NULL, 'n' }, { "bf_name", 0, NULL, 'b' }, { "love", 1, NULL, 'l' }, { 0, 0, 0, 0}, }; int main(int argc, char *argv[]) { int c; while((c = getopt_long (argc, argv, short_options, long_options, NULL)) != -1) { switch (c) { case 'n': printf("My name is XL.\n"); break; case 'b': printf("His name is ST.\n"); break; case 'l': l_opt_arg = optarg; printf("Our love is %s!\n", l_opt_arg); break; } } return 0; } [root@localhost wyp]# gcc -o getopt getopt.c [root@localhost wyp]# ./getopt -n -b -l forever My name is XL. His name is ST. Our love is forever! [root@localhost liuxltest]# [root@localhost liuxltest]# ./getopt -nb -l forever My name is XL. His name is ST. Our love is forever! [root@localhost liuxltest]# ./getopt -nbl forever My name is XL. His name is ST. Our love is forever!

總結(jié)

以上是生活随笔為你收集整理的linux 之 getopt_long()的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。