【问题标题】:How does getopt(3) work, and what is the 'extern' variable optarg?getopt(3) 是如何工作的,'extern' 变量 optarg 是什么?
【发布时间】:2014-04-30 23:55:29
【问题描述】:

我正在尝试学习如何接受命令行参数和伴随标志的数据,即

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;
        }
    }
}

我的输出:($ myprogram -p test)

cvalue is : (null)

【问题讨论】:

  • +1 恭喜您提出了格式正确的问题。
  • 谢谢!第一个也是!
  • 欢迎来到 SO。如果这是第一个待解决的问题,我鼓励您使用“真实”用户名。我倾向于忽略用户 NNNNNNN 的问题,因为这些问题的质量普遍较低,并且会被问到“为我做我的工作”。
  • @StephenP 我有相反的经历;就我个人而言,我从不根据句柄对问题进行评分。
  • @self — 我不根据句柄 评分,但我不太可能将时间花在“路过”问题上 — 有很多来自匿名用户的坏消息,他们在询问之前懒得搜索,我厌倦了浪费我仅有的一点“空闲”时间。

标签: c unix getopt


【解决方案1】:

来自the manual

此字符串中的选项字符后面可以跟一个冒号(‘:’),表示它需要一个必需的参数。

因此,在您的情况下,您的选项字符串应该是 "p:s" 而不是 "ps"

【讨论】:

  • 有效!谢谢!在你发表评论后我才想通!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多