DAnsermino
DAnsermino

Reputation: 383

optarg from getopt() is always null

I'm trying to process an argument parameter using the optarg parameter of getopt(), but it remains null. Could this be something to do with the c99 standard? I know I will need to actually copy the string from optarg but it never even gets set.

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

Upvotes: 0

Views: 1707

Answers (1)

mike
mike

Reputation: 1

optarg is something that's initialized by a call to getopt(), you're overwriting it by initializing it yourself. Remove the line "char* optarg;" and you should be good to go.

Upvotes: 0

Related Questions