Osdc Cheatsheet-C Getopt-2021.8.10
Osdc Cheatsheet-C Getopt-2021.8.10
To parse command-line short options in C, use getopt() with argc and argv.
#include <unistd.h>
int getopt(int argc, char * const *argv, const char *optstring);
Global variables
extern int opterr If 0, turn off error messages (default is non-zero)
extern int optopt An unrecognized option (if getopt() returns ?)
extern char *optarg Arg to option (if option letter in optstring is followed by :)
extern int optind The next element in argv after getopt() is done
getopt() returns the letter from optstring if found, ? if unrecognized, or -1 if no options left.
#include <stdio.h>
#include <unistd.h>
To parse command-line long options in C, use getopt_long() with argc and argv.
#include <getopt.h>
int getopt_long(int argc, char * const *argv, const char *optstring,
const struct option *longopts, int *longindex);
struct option {
const char *name;
int has_arg;
int *flag;
int val; };
Global variables
longopts.name The name of the long option (such as "help" or "option")
longopts.has_arg If 0, no optarg. If 1, requires an optarg. If 2, optional optarg
longopts.flag Returns val or 0
longopts.val The value returned (such as 'h' or 'o')
longindex Points to a variable to store the index of the long option in longopts