简体   繁体   中英

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):

  • -f
  • --filename

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

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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