Is there a way to use getopt when flags arent at the beginning?

84 Views Asked by At

A C program I am writing takes files and flags as arguments. The program needs to support flags being placed anywhere amongst the arguments. So, for example, "./program file1 file2 -f 10 file3 file4". I'm trying to use getopt() and optarg to read flags. But I can't get it to work without placing the flags as the first agruments.

If tried the simple

int c;
while ((c = getopt(argc, argv, "jB")) != -1)
{
    switch (c)
    {
    case 'j':
        jflag = true;
        break;
    case 'B':
        bflag = true;
        break;
    default:
    }
}

But it stops as soon as an argument isn't a flag. I've also tried using to force getopt past this:

int opt;
int number = 1;

for (int i = 0; i < argc; i++)
{
    opt = getopt(argc, argv, "j:");
    if(opt == 'j')
    {
        number = atoi(optarg);
    }
}

And I can't get it to work. Is there any way to do this without having the flags as the first arguments?

NOTE: Disregard the fact that the code examples do slightly different things. None of the examples find any flag.

1

There are 1 best solutions below

0
John Bollinger On

I'm trying to use getopt() and optarg to read flags. But I can't get it to work without placing the flags as the first agruments.

getopt() is not documented in the C language spec. The POSIX specifications for it prescribe the behavior you observe: option processing stops at the first non-option argument.

GNU getopt() does behave by default as you seem to want, but if you can't rely that version then you probably need to write your command-line processing without relying on getopt(). In fact, because getopt() is non-standard (with respect to the language spec), you probably should avoid it altogether if you need your program to be widely portable.