c++命令行解析库cmdline使用

之前用过 getopt 函数对主函数参数进行解析,后发现了 cmdline 这个库——说是库,实际只是一个头文件,非常方便集成到程序中。本文对此库进行简单测试。

下载编译

cmdline 库地址为:https://github.com/tanakh/cmdline
可直接下载 cmdline.h 头文件使用,也可以下载仓库,编译其中的测试示例。

测试

测试代码

测试代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*

如果解析不存在的参数,会报段错误,最好加默认值

TODO:添加子命令,类似 git log、git status 这样的
*/

#include "cmdline.h"

#include <stdio.h>
#include <iostream>
using namespace std;

bool g_bPrint = false;

// 有些帮助信息过多,使用函数组装
char* getHelp(int type)
{
static char info[256] = {0};
if (type == 't')
{
sprintf(info,
" test type \n \
autotest - for auto test\n \
dualtest - for dual version test\n \
more comming up...");
}

return info;
}

int main(int argc, char *argv[])
{
cmdline::parser theArgs;
// 一般形式:长命令名、短命令名(如不支持短命令填'\0'),描述,是否必填,默认值
// 如果为必填,则在运行时必须带该参数,否则解析失败
theArgs.add<string>("test", 't', getHelp('t'), false, "auto");
theArgs.add<string>("host", 'h', "host name", false, "");
theArgs.add<int>("rate", 'r', "rate number", false, 80, cmdline::range(1, 65535)); // 带默认值、范围的

// bool 型,与上述不同,后判断有无该参数
theArgs.add("print", 'p', "show message"); // 需要判断是否存在,存在则置标志为true

//theArgs.add("help", 0, "print this message1111");

//theArgs.footer("filename ...");
//theArgs.set_program_name("mytool");
theArgs.set_program_name(argv[0]);

// 调整位置,让cmdline误以为第二个参数才是命令
//theArgs.parse_check(argc-1, &argv[1]);

try{
printf("test type: %s\n", theArgs.get<string>("test").c_str());
} catch(const std::exception &e){}
try{
printf("bad: %s\n", theArgs.get<string>("bad").c_str()); // 不存在的参数
} catch(const std::exception &e){
printf("param [bad] not exist...\n");
}
try{
printf("host: %s\n", theArgs.get<string>("host").c_str());
} catch(const std::exception &e){}
try{
printf("rate: %d\n", theArgs.get<int>("rate"));
} catch(const std::exception &e){}

try{
printf("rest args: \n");
for (int i = 0; i < (int)theArgs.rest().size(); i++)
{
//cout << theArgs.rest()[i] << endl;
printf("%s\n", theArgs.rest()[i].c_str());
}
} catch(const std::exception &e){}

// 此法不能判断不存在的参数
// if (theArgs.exist("type"))
// {
// printf("type111: %d\n", theArgs.get<string>("type").c_str());
// }

//
if (theArgs.exist("rate")) // 非bool类型,似乎也不能如此判断
{
printf("rate111: %d\n", theArgs.get<int>("rate"));
}

if (theArgs.exist("print"))
{
g_bPrint = false;
}
return 0;
}

输出结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ ./a.out 
argument number must be longer than 0
usage: ./a.out [options] ...
options:
-t, --test test type
autotest - for auto test
dualtest - for dual version test
more comming up... (string [=auto])
-h, --host host name (string [=])
-r, --rate rate number (int [=80])
-p, --print show message
-?, --help print this message

$ ./a.out -r 100 -h latelee.org
test type: auto
param [bad] not exist...
host: latelee.org
rest args:
100