简体   繁体   English

getopt()中的optarg始终为null

[英]optarg from getopt() is always null

I'm trying to process an argument parameter using the optarg parameter of getopt(), but it remains null. 我正在尝试使用getopt()的optarg参数处理参数参数,但是它保持为空。 Could this be something to do with the c99 standard? 这可能与c99标准有关吗? I know I will need to actually copy the string from optarg but it never even gets set. 我知道我实际上需要从optarg复制字符串,但是它永远都不会被设置。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *optarg;
    int ch; 

    char *indir = NULL;

    while ((ch = getopt(argc, argv, "d:")) != -1) {
        switch(ch) {
            case 'd':
                indir = optarg;
                fprintf(stderr, "Optarg: %s\n", optarg);
                fprintf(stderr, "Dir name: %s\n", indir);
                break;
            default : 
                fprintf(stderr, "Usage:  test -d <input directory>\n");
                exit(1);
        }
    }
    if(indir == NULL){
        fprintf(stderr, "Input directory required.\n");
        exit(1);
    }
    else{
        printf("Input dir: %s\n", indir);
    }


    return 0;
}

optarg is something that's initialized by a call to getopt(), you're overwriting it by initializing it yourself. optarg是通过调用getopt()初始化的东西,您可以通过对其进行初始化来覆盖它。 Remove the line "char* optarg;" 删除行“ char * optarg;” and you should be good to go. 而且你应该很好走。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM