Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getopt - filename as argument

Tags:

c

unix

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?

like image 732
user461316 Avatar asked Mar 04 '11 01:03

user461316


2 Answers

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)

like image 199
Steve Jessop Avatar answered Sep 29 '22 10:09

Steve Jessop


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.

like image 35
chrisaycock Avatar answered Sep 29 '22 12:09

chrisaycock