【发布时间】:2017-09-06 10:31:55
【问题描述】:
当我传递任何参数时,我得到这个错误:分段错误(核心转储) 只有 -h 选项可以正常工作。
此处选项 -d 和 -a 采用字符串值。
选项 -s 和 -e 取整数值。
如何保存传递给不同变量的选项值以供以后使用?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
void usage() {
printf("Usage: help\n----------\n------");
}
int main(int argc, char *argv[]) {
int opt= 0;
int start = -1, end = -1;
char *alg,*dir;
static struct option long_options[] = {
{"start",no_argument,0,'s' },
{"end",no_argument,0,'e' },
{"algorithm",no_argument, 0,'a' },
{"directory",required_argument, 0,'d' },
{0,0,0,0}
};
int long_index =0;
while ((opt = getopt_long(argc, argv,"seadh:",
long_options, &long_index )) != -1) {
switch (opt) {
case 'a' :
printf("you entered \"%s\"\n", optarg); // error while printing this
break;
case 'd' :
printf("you entered \"%s\"\n", optarg);
break;
case 's' : start = atoi(optarg);
break;
case 'e' : end = atoi(optarg);
break;
case 'h' : usage();
break;
default: usage();
exit(EXIT_FAILURE);
}
}
printf("%d",start);
return 0;
}
我想使用传递的选项及其值在这个 C 程序中使用 system Call 调用 python 脚本。
例如:系统(python alg.py -alr -s3 -e45 -d/path)
【问题讨论】:
-
{"algorithm",no_argument, 0,'a' }-->{"algorithm",required_argument, 0,'a' }(与s、e相同)和"seadh:"-->"s:e:a:d:h" -
等等……你真的需要“帮助”的论据,而不是反过来?
-
@BLUEPIXY "s:e:a:d:h" 这行得通,但是如何将此选项值保存到不同的变量中?我的主要要求是将其发送到在 c 程序中调用的 python 脚本的选项。在代码之后阅读问题的结尾部分,我该怎么做?
-
@BLUEPIXY {"algorithm",no_argument, 0,'a' } --> {"algorithm",required_argument, 0,'a' } , option a, s and e are optional , only -d 选项是必须的,所以我还需要将所有其他选项设为 required_argument 吗?
-
@programmer 我选择相信文档。
标签: c arguments getopt getopt-long