Linux运行app带参数 [getopt]
Angie An

Linux运行app带参数 getopt

头文件:#include <getopt.h>

main函数中:

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
int opt = 0;
int cmd = 0;
int data = 0;
const char *optstring = "a:b:c:hz";
//while ((opt = getopt_long(argc, argv, optstring)) != -1)
while ((opt = getopt(argc, argv, optstring)) != -1)
{
case 'a': //analog voltage
sscanf(optarg, "%d", &data);
break;
case 'b': //set bar
sscanf(optarg, "%d", &data);
break;
case 'c': // do api func
printf("opt is c, comand is: %s\n", optarg);
if (!strcmp(optarg, "open"))
{
cmd = 1;
}
else if (!strcmp(optarg, "close"))
{
cmd = 2;
}
else
{
printf("[ERR] command NG: %s\n", optarg);
return 0;
}
/*
ret = do_api_func(cmd);
if (0 != ret)
{
printf("[ERR] errcode=%d\n", ret);
return 0;
}
else
{
ret = check_api_result_when_ok(cmd);
}
break;
*/
case 'z': //dump parameters for debug
//debug_dump_api_parameters();
break;
case 'h':
print_usage(argv[0]);
return 0;
case '?':
printf("Try \'%s -h\' for more information.\n", argv[0]);
return 0;
}

如果想用长命令(–command)代替短命令(-c),使用转换:

1
2
3
4
5
6
struct option long_options[] = {
{"cmd", 1, NULL, 'c'},
{"analog-input", 1, NULL, 'a'},
{"bar", 1, NULL, 'b'},
{0, 0, 0, 0},
};
 Comments