我正在尝试学习如何接受命令行参数和标记后的伴随数据,即
myprogram -sampleflag datahere
我的代码到目前为止。 getopt()将数据抛出到变量 c 中,显然您可以从调用它的函数外部访问 optarg 。这怎么可能?根据手册页,我的代码应该工作!但是,如您所见,输出为(null)。
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
opterr = 0;
char* cvalue = NULL;
int c;
char* optarg = hello;
while((c = getopt(argc, argv, "ps")) != -1){
switch(c){
case 'p':
cvalue = optarg;
printf("cvalue is : %s\n", cvalue );
break;
}
}
}
cvalue is : (null)
答案 0 :(得分:4)