【发布时间】:2016-09-23 07:37:02
【问题描述】:
我很难将 getopt 操作设为可选。这是我的代码的一部分。它接受一个参数文件,如果存在,它会计算字符数。如果不是,它会计算 stdinput 字符。
我的问题是 optarg 在未声明后设置为什么?以及如何使我的选项 -c 可选并使其工作。
目前它总是从标准输入读取。
while( (option = getopt(argc, argv, "c::") ) != -1 ) {
switch(option) {
case 'c':
if (optarg == NULL) {
file = stdin;
}
else {
file = fopen(optarg, "r");
}
while( (ch = fgetc(file)) != EOF ) {
count++;
}
printf("%d %s\n", count, optarg);
fclose(file);
break;
【问题讨论】:
-
"
optarg未声明后将设置为什么"???你再清楚不过了。 -
为什么是
::,而不是:? -
"两个冒号表示一个选项需要一个可选参数" - linuxmanual
-
对不起,如果我不清楚。 I am clarifying whether optarg get set to NULL when the option -c becomes optional.我认为这可能是为什么这是错误的,因为当我打印 optarg 时,它会给出 Seg Fault
-
我不知道这个 GNU 扩展。请查看我的更新答案。