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(argc, argv, optstring)) != -1) { case 'a': sscanf(optarg, "%d", &data); break; case 'b': sscanf(optarg, "%d", &data); break; case 'c': 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; }
case 'z': 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}, };
|