Getopt - file name as argument

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

./something -d dopt filename 

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

What is the getopt form for representing get filename?

+4
source share
2 answers

Use optstring "d:"

Grab -d dopt with optarg usual way. Then look at optind (compare it with argc ), which indicates if there are any optional arguments. If so, your file name is the first one.

getopt does not specifically tell you that arguments have no argument or check the number. It just tells you where they start (first moved them to the end of the argument array if you are in GNU mode)

+4
source

Refuse how grep does this . At the end of main() you will find:

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

optind is the number of command line options found by getopt. Thus, this conditional / contour design can process all files listed by the user.

+2
source

Source: https://habr.com/ru/post/1342216/


All Articles