最近看代码,发现居然有这个getopt_long函数,然后:
参考链接:个人感觉这个解释的比较好
命令行解析函数:getopt_long、getopt - 掘金
下面是我个人做的一些测试
- #include
- #include
- #include
-
- int main(int argc, char *argv[]) {
- int c;
- static struct option long_options[] = {
- {"help", no_argument, 0, 'h'},
- {"input", required_argument, 0, 'i'},
- {"output", required_argument, 0, 'o'},
- {0, 0, 0, 0}
- };
-
- while ((c = getopt_long(argc, argv, "c:i::s:droht", long_options, NULL)) != -1) {
- switch (c) {
- case 'c':
- printf("Option -c with value '%s'\n", optarg);
- break;
- case 'i':
- printf("Option -i with value '%s'\n", optarg);
- break;
- case 's':
- printf("Option -s with value '%s'\n", optarg);
- break;
- case 'd':
- printf("Option -d\n");
- break;
- case 'r':
- printf("Option -r\n");
- break;
- case 'o':
- printf("Option -o\n");
- break;
- case 'h':
- printf("Option -h\n");
- break;
- case 't':
- printf("Option -t\n");
- break;
- default:
- printf("Unknown option\n");
- break;
- }
- }
-
- // 处理未在循环中处理的参数
- for (int i = optind; i < argc; i++) {
- printf("Non-option argument: %s\n", argv[i]);
- }
-
- return 0;
- }
运行
./a.out -c config.txt -i input.txt --s 1024 -d -r --output 00 -h -t arg1 arg2

发现-i有问题,无法输出,改成

说明:
单个字符,表示没有参数
单个字符紧跟1个冒号,表示必须有参数**,格式:-d xxx或者-dxxx**
单个字符紧跟2个冒号,表示参数可选**,格式:-dxxx**
Char *optstring="ab:c::";
说明:此选项指定了三个选项,分别为'a'、'b'、'c'。其中
a选项无需参数,格式:-a即可
b选项必须有参数,格式:-d xxx
c选项参数可选,格式:-c ooo