在 C 中解析具有共同标志的选项
Parsing options having a common flag in C
我有一个接受多个参数的 C 程序。在这里,我有一个通用标志 d
用于数据存储和磁盘。在检查大小写 d
之前,有没有一种方法可以按顺序检查标志并获取 store
的值。我尝试了各种方法,比如在此之前添加一个 while 循环来检查 s
然后进入此循环等
static void
ParseOptions(int argc, char* argv[])
{
int c, option_index;
int ind = 0;
while((c = getopt_long(argc, argv, "s:d:",
long_options, &option_index))!= -1) {
ind = optind;
switch(c) {
case 's':
optionStore = true;
store = strdup(optarg);
break;
case 'd':
if(strcmp(store,"datastore") == 0){
printf("In datastore\n");
datastore = strdup(optarg);
}
else if(strcmp(store,"disk") == 0){
printf("In disk\n");
disk = strdup(optarg);
}
break;
default:
exit(-1);
}
}
}
不知道该怎么做。
您需要将标志 d
返回的 optarg
存储在一个临时变量中,并在循环退出后使用它来设置 disk
或 datastore
:
char *temp_disk_or_datastore;
while((c = getopt_long(argc, argv, "s:d:",
long_options, &option_index))!= -1) {
ind = optind;
switch(c) {
case 's':
optionStore = true;
store = strdup(optarg);
break;
case 'd':
temp_disk_or_datastore = strdup(optarg);
break;
default:
exit(-1);
}
}
if (store == NULL) {
printf("Missing storage option");
exit(-1);
}
if(strcmp(store,"datastore") == 0){
printf("In datastore\n");
datastore = temp_disk_or_datastore;
}
else if(strcmp(store,"disk") == 0){
printf("In disk\n");
disk = temp_disk_or_datastore;
}
我有一个接受多个参数的 C 程序。在这里,我有一个通用标志 d
用于数据存储和磁盘。在检查大小写 d
之前,有没有一种方法可以按顺序检查标志并获取 store
的值。我尝试了各种方法,比如在此之前添加一个 while 循环来检查 s
然后进入此循环等
static void
ParseOptions(int argc, char* argv[])
{
int c, option_index;
int ind = 0;
while((c = getopt_long(argc, argv, "s:d:",
long_options, &option_index))!= -1) {
ind = optind;
switch(c) {
case 's':
optionStore = true;
store = strdup(optarg);
break;
case 'd':
if(strcmp(store,"datastore") == 0){
printf("In datastore\n");
datastore = strdup(optarg);
}
else if(strcmp(store,"disk") == 0){
printf("In disk\n");
disk = strdup(optarg);
}
break;
default:
exit(-1);
}
}
}
不知道该怎么做。
您需要将标志 d
返回的 optarg
存储在一个临时变量中,并在循环退出后使用它来设置 disk
或 datastore
:
char *temp_disk_or_datastore;
while((c = getopt_long(argc, argv, "s:d:",
long_options, &option_index))!= -1) {
ind = optind;
switch(c) {
case 's':
optionStore = true;
store = strdup(optarg);
break;
case 'd':
temp_disk_or_datastore = strdup(optarg);
break;
default:
exit(-1);
}
}
if (store == NULL) {
printf("Missing storage option");
exit(-1);
}
if(strcmp(store,"datastore") == 0){
printf("In datastore\n");
datastore = temp_disk_or_datastore;
}
else if(strcmp(store,"disk") == 0){
printf("In disk\n");
disk = temp_disk_or_datastore;
}