# Resolve arguments from command line ###### tags: `C` `C++` ## getopt and getopt_long The getopt() function parses the command-line arguments. Its arguments argc and argv are the argument count and array as passed to the main() function on program invocation. ```c++=50 #include <unistd.h> int getopt(int argc, char *const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; #include <getopt.h> int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex); int getopt_long_only(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex); ``` ### arguments 1. **argc, argv** argc and argv are the argument count and array as passed to the main() function on program invocation. An element of argv that starts with '-' is an option element. The characters of this element(aside from '-') are option characters. Ex: ```c++=50 ./test.out -v // -v is a option element, v is a option character ``` 2. **optind** The variable optind is the index of the next element to be processed of argv. The initial value of optind is 1 and it can be reset when rescanning the same argv is needed. 3. **optstring** optstring is a string containing legitimate **option characters**. If such character is **followed by a colon**, the corresponding option **requires an argument** which will be assigned to variable **optarg**. If such character is followed by two colons, the corresponding argument of the option is optional. The special argument **"--" forces an end** of option-scanning regardless of the scanning mode. optstring EX: ```c++ "a:bc" // optstring ``` Code: ```c++ #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int ch; while((ch = getopt(argc, argv, "a:b")) != -1) { switch(ch) { case 'a': printf("option a: %s\n", optarg); break; case 'b': printf("option b \n"); break; case '?': //when option error printf("unknown option \n"); break; default: printf("default \n"); } } } ``` Input: ``` ./test -a aa -b -c ``` Output: ```c++ option a: aa option b unknown option ``` By default, getopt() prints an error message on standard error, places the erroneous option character in optopt, and returns '?' as the function result. ### getopt_long The getopt_long() function works like getopt() except that it also **accepts long options**, started with **two dashes**. (If the program accepts only long options, then optstring should be specified as an empty string (""), not NULL.) **longopts** is a pointer to the first element of an array of struct option declared in **<getopt.h>** as ```c++ struct option { const char *name; //name of the long option int has_arg; //0: no argument, 1: require argument, 2: optionalo int *flag; int val; }; ```