jamal
jamal

Reputation: 573

Parsing option arguments in terminal using getopt_long in C

I'm just having a problem when parsing my option arguments through terminal. When executing my c file, I can only have one option which is the file name. I can enter the file name with two options (a short option and a long option):

and they both need the file name as argument. When I execute the program with "-f" and "--filename", it works fine but when I test "-filename", it doesn't give me error saying "the usage is ..." and it counts the argument of this option as one of the non-option arguments of main (I don't know if I expressed it well) Can anyone help me with that? How can I handle this? How to tell the user this is not the correct option? This is my code so far:

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

static struct option longopts[] = {
    {"filename",  required_argument, 0, 'f'},
    {0, 0, 0, 0}
};

int main(int argc, char **argv) {
    int res;
    int indexptr;
    char *filename;
    while ((res = getopt_long(argc,argv,"f:",longopts,&indexptr)) != -1)
    {
        switch(res)
        {
        case 'f':
            filename = optarg; // the file is now in optarg 
            break;

        default: /* '?' */
            fprintf(stderr, "Usage: %s <[-f/--filename Filename]> <D> <U>\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }
}

Thanks

Upvotes: 0

Views: 359

Answers (1)

Random832
Random832

Reputation: 39080

When you do -filename (with one dash), most getopt implementations will treat it the same as -f ilename (which is not an error). If you had printed out what it thinks the filename argument is you would have seen "ilename".

Upvotes: 1

Related Questions