user461316
user461316

Reputation: 913

Getopt - filename as argument

Let's say I made a C program that is called like this:

./something -d dopt filename

So -d is a command, dopt is an optional argument to -d and filename is an argument to ./something, because I can also call ./something filename.

What is the getopt form to represent get the filename?

Upvotes: 5

Views: 9112

Answers (2)

chrisaycock
chrisaycock

Reputation: 37930

Check-out how grep does it. At the end of main() you'll find:

if (optind < argc)
{
    do
    {
        char *file = argv[optind];
        // do something with file
    }
    while ( ++optind < argc);
}

The optind is the number of command-line options found by getopt. So this conditional/loop construct can handle all of the files listed by the user.

Upvotes: 4

Steve Jessop
Steve Jessop

Reputation: 279305

Use optstring "d:"

Capture -d dopt with optarg in the usual way. Then look at optind (compare it with argc), which tells you whether there are any non-option arguments left. If so, your filename is the first of these.

getopt doesn't specifically tell you what the non-option arguments are or check the number. It just tells you where they start (having first moved them to the end of the argument array, if you're in GNU's non-strict-POSIX mode)

Upvotes: 4

Related Questions