Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The C language provides the function <strong>getopt</strong> to parse command-line options. The <strong>getopt_long</strong> function is a GNU extension that parses command-line options that offer more functionality than <strong>getopt</strong> such as multi-character options parsing. You can find documentation here : <a href="http://linux.die.net/man/3/getopt_long" rel="nofollow">http://linux.die.net/man/3/getopt_long</a> or simply a man <strong>getopt_long</strong>. Let me show an example. Let's say you have a program that have 3 options (-h for help message, -i for displaying an integer and -s for displaying a String). First, you must declare a <strong>struct options</strong>. This structure will contains all options that your program needs and is defined like this :</p> <pre><code> struct option { const char *name; // the option name int has_arg; // if your option has an argument - no_argument (equivalent to 0) if no option and required_argument otherwise (1) int *flag; // specifies how results are returned for a long option. If flag is NULL, then getopt_long() returns val int val; // is the value to return, or to load into the variable pointed to by flag. }; </code></pre> <p>As your program as many options, you must declare an array of struct options :</p> <pre><code>struct option options[] = { {"help", no_argument, NULL, 'h'}, // for the help msg {"int", 1, required_argument, 'i'}, // display an int {"string", required_argument, NULL, 's'}, // displays a string {NULL, 0, NULL, 0}}; </code></pre> <p>And you read your options as follow :</p> <pre><code> int main(int argc, char* argv[]){ char opt; while ((opt = getopt_long (argc, argv, "his:", options, NULL)) != -1) { switch(opt){ case 'h': printf("Help message \n"); exit(0); case 'i': printf("Int options = %d\n", optarg);break; case 's': printf("String option = %s\n", optarg); break; default: printf("Help message\n"); } } </code></pre> <p>Don't forget to include <strong>"getopt.h"</strong></p> <p>Good Luck</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload