getopt 是 POSIX 標準的命令行選項解析器,支援短選項(-x)、帶參選項(-t 100)、選項合併(-nt 100)。
#include <unistd.h> int getopt(int argc, char *const argv[], const char *optstring); extern char *optarg; // 當前選項的參數 extern int optind; // 下一個待解析 argv 索引 extern int opterr; // 是否打印錯誤信息(默認 1) extern int optopt; // 最後一個未識別的選項字符
"nt:" 表示 -n 無參,-t 有參)。::該選項**必須**有參數,參數存入 optarg。::(GNU 擴展):選項參數**可選**。#include <stdio.h>
#include <stdlib.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 ((opt = getopt(argc, argv, "nt:")) != -1) {
switch (opt) {
case 'n':
puts("AAAAAAAA");
break;
case 't':
puts("BBBBBBBB");
int n = atoi(optarg);
printf("n = %d\n", n);
break;
case '?': // 未識別選項或缺參
case ':': // 缺參(opterr=0 時)
ERR_EXIT("Invalid option");
}
}
// 剩餘非選項參數:argv[optind]...
return 0;
}
$ ./a.out -n AAAAAAAA $ ./a.out -t ./a.out: option requires an argument -- 't' $ ./a.out -t 100 BBBBBBBB n = 100
opterr = 0:關閉默認錯誤輸出,自行處理 '?'/':'。optind 循環後指向第一個非選項參數,可處理命令文件列表。--help)需用 getopt_long(GNU 擴展)。getopt 輕量、可移植,是 C 程序處理命令行的首選工具。