Reordering Arguments

submited by
Style Pass
2021-06-23 10:30:09

When a C program runs, it usually receives any command-line arguments through the parameters argc (argument count) and argv (argument vector). It is up to the program to interpret the contents of this array of strings.

There are many ways to do this, one of the simpler solutions is the getopt function (in the following, getopt will refer to both getopt and getopt_long). One extension some getopt implementations offer, is that they reorder the contents of argv as they process it, resulting in an array where all the options appear first followed by the nonoptions.

This reordering partitions the array. And we want a stable partition, so the relative order of all the options, and of all the nonoptions is the same.

Last year I released parg, a simple parser for argv that works similarly to getopt. It has a separate function, parg_reorder(), that performs this reordering. I used a simple algorithm for this – allocate a temporary array the size of argv, parse the arguments, and fill in the options from the start and nonoptions from the end of the new array. Then copy them back, reversing the nonoptions to their original order in the process. In hindsight, I could have moved the options into their final place in argv right away.

This runs in time, but also requires additional space. The space requirement could be a problem (for instance on embedded systems), so let’s see if we can do better.

Leave a Comment