Linux下面的C語言使用getopt Parse Command Line參數
getopt(3) – Linux man page

What is getopt()

The getopt() function parses the command-line arguments. Inputs are argc, argv and legitimate option characters. Output is the next option character.


#include <unistd.h>

int getopt(int argc, char * const argv[],
           const char *optstring);

extern char *optarg;
extern int optind, opterr, optopt;

Arguments and variables

  • int argc:
    • argument count
  • char * const argv[]
    • argument vector as passed to the main() function on program invocation
    • contain argv-elements
  • const char *optstring
    • optstring is a string containing the legitimate option characters.
    • An element of argv that starts with ‘-‘ is an option element. The characters of this element (aside from the initial ‘-‘) are option characters. 選項用一個dash”-“開頭。
    • format
      • a signal character
        • the option requires no argument
      • a signal character followed by a colon
        • the option requires an argument
      • a signal character followed by two colons
        • The argument is optional
      • example: “abcd:e::”
        • ./cmd -a -b -c -d arg1 -e [arg2]
  • int optind
    • The index of the next element to be processed in argv.
    • This is used to handle the non-option arguments by comparing it to argc.
  • int optopt
    • If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns ‘?’.
  • char *optarg
    • the option argument
    • when the option has an argument, the argument will be assign to this variable.

Leave a Reply

Close Menu