利用getopt_long()為程序傳入參數
man getopt_long,得到其聲明如下:
int getopt_long(int argc, char * const argv[],const char *optstring, const struct option *longopts,int *longindex);函數中的argc和argv通常直接從main()的兩個參數傳遞而來。optsting是選項參數組成的字符串:
字符串optstring可以下列元素:
1.單個字符,表示選項,
2.單個字符後接一個冒號:表示該選項後必須跟一個參數。參數緊跟在選項後或者以空格隔開。該參數的指針賦給optarg。
3 單個字符後跟兩個冒號,表示該選項後可以有參數也可以沒有參數。如果有參數,參數必須緊跟在選項後不能以空格隔開。該參數的指針賦給optarg。(這個特性是GNU的擴張)。
參數longopts,其實是一個結構的實例:
struct option { const char *name; //name表示的是長參數名 int has_arg; //has_arg有3個值,no_argument(或者是0),表示該參數後麵不跟參數值, required_argument(或者是1),表示該參數後麵一定要跟個參數值, optional_argument(或者是2),表示該參數後麵可以跟,也可以不跟參數值 int *flag;//用來決定,getopt_long()的返回值到底是什麼。如果flag是null,則函數會返回與該項option匹配的val值 int val; //和flag聯合決定返回值 }
小例子:
#include <stdio.h> #include <getopt.h> #include <stdlib.h> /*單個字符,表示選項,單個字符後接一個冒號:表示該選項後必須跟一個參數。 參數緊跟在選項後或者以空格隔開。該參數的指針賦給optarg。 optarg不需要定義,在getopt.h中已經有定義)*/ char* const short_options = "hnd:g:"; struct option long_options[] = { { "help", 0, NULL, 'h'}, { "no", 0, NULL, 'n' }, { "long", 1, NULL, 'd' }, { "long", 1, NULL, 'g'}, { 0, 0, 0, 0}, }; void print_usage(FILE *stream) { fprintf(stream, "Usage: option [ dev... ] \n"); fprintf(stream, "\t-h --help Display this usage information.\n" "\t-n --no_argument No argument is running\n" "\t-g --傳遞ip\n" "\t-d --DEBUG\n"); exit(0); } int main(int argc, char *argv[]) { int c = 0; char *dbgbuf = NULL; char *ipbuf = NULL; if(argc < 2){ print_usage(stdout); } while((c = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) { switch (c) { case 'g': ipbuf = optarg; printf("ip=%s\n", ipbuf); break; case 'h': print_usage(stdout); break; case 'n': printf("no_argument\n"); break; case 'd': dbgbuf = optarg; printf("debug is %s!\n", dbgbuf); while(1) { if(strcmp(dbgbuf, "GPSON")==0) printf("gps printf is runing\n"); sleep(1); } break; default: break; } } return 0; }

最後更新:2017-04-03 14:54:06