Linux提供了一個解析命令行參數的函數。
#include <unistd.h>
int getopt(int argc, char * const argv[],
const char *optstring);
extern char *optarg;
extern int optind, opterr, optopt;
使用這個函數,我們可以這樣運行命令
./a.out -n -t 100
n後面不需要參數,t需要一個數值作為參數。
代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define ERR_EXIT(m) \
do { \
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
int main(int argc, char *argv[])
{
int opt;
while(1)
{
opt = getopt(argc, argv, "nt:");
if(opt == '?')
exit(EXIT_FAILURE);
if(opt == -1)
break;
switch(opt)
{
case 'n':
printf("AAAAAAAA\n");
break;
case 't':
printf("BBBBBBBB\n");
int n = atoi(optarg);
printf("n = %d\n", n);
}
}
return 0;
}
當輸入非法參數時,getopt返回’?’,當解析完畢時,返回-1.
如果需要參數,那麼使用optarg獲取,這是一個全局變量。
注意getopt的第三個參數”nt:”,說明可用的參數有n和t,t後面有一個冒號,說明t需要額外的參數。
運行結果如下:
5:30:22 wing@ubuntu msg ./getopt_test -n AAAAAAAA 5:30:26 wing@ubuntu msg ./getopt_test -t ./getopt_test: option requires an argument -- 't' 5:30:31 wing@ubuntu msg ./getopt_test -t 100 1 ↵ BBBBBBBB n = 100