Skip to content
Tutorials Center
My learning

Topics

C Reference ยท POSIX and Systems

C getopt() function

Reference for getopt() and getopt_long(): parse short and long command-line options, handle option arguments, optind, unknown options and error messages.

getopt() parses the options of a command line such as tool -v -o out.txt input.txt. Each call returns the next option character, and sets a few global variables so you can fetch the option's argument and find where the plain arguments start. You describe the legal options in one string.

getopt_long() (a GNU and BSD extension, in glibc) adds long options like --verbose and --output=out.txt. Both live in <unistd.h> / <getopt.h> and are not part of ISO C: on Windows use a small hand-written parser or a library.

C
#include <unistd.h>

int opt;
while ((opt = getopt(argc, argv, "vo:")) != -1) {
    /* opt is 'v', 'o' (optarg set) or '?' for an error */
}

Try it

C Short options with a fake command line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Long options with getopt_long

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
int getopt(int argc, char *const argv[], const char *optstring);
int getopt_long(int argc, char *const argv[], const char *optstring,
                const struct option *longopts, int *longindex);

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

struct option {
    const char *name;
    int         has_arg;   /* no_argument, required_argument, optional_argument */
    int        *flag;
    int         val;
};
Name Description
argc, argv The arguments, normally straight from main.
optstring The legal short options. A letter followed by : takes an argument ("vo:"). A leading : suppresses error messages and makes a missing argument return : instead of ?.
longopts An array of struct option ending with an all-zero entry.
longindex Optional; receives the index of the matched long option.
optarg Points to the current option's argument.
optind Index of the next argv element to process. After parsing, argv[optind] is the first operand.
opterr Set to 0 to stop getopt printing its own messages.
optopt The offending character after an unknown option or missing argument.

Returns: the option character, '?' for an unknown option or missing argument (or ':' for a missing argument when optstring starts with a colon), and -1 when the options are used up.

Errors / undefined behavior: none for ordinary use. Calling getopt with a different argv or after changing argv mid-scan gives unspecified results; to rescan, set optind = 1 (glibc also accepts 0).

Usage notes

  • Global state. getopt keeps its position in global variables, so it is not thread-safe and cannot parse two command lines at once. Reset optind before reusing it.
  • Argument permutation. glibc moves operands to the end, so tool file -v still sees -v. POSIX behavior stops at the first operand; set POSIXLY_CORRECT or begin optstring with + to get it. BSD and macOS stop at the first operand.
  • -- ends option processing; everything after it is an operand.
  • Grouped options. -vo out.txt is the same as -v -o out.txt, and -oout.txt also works.
  • Validate arguments. optarg is just a string; convert numbers with strtol and check for errors.
  • Messages. By default getopt prints a message to stderr for an unknown option. Library code or tools with their own style should set opterr = 0.
  • main changed argv? The array is char *const argv[] but glibc may reorder its elements; do not depend on the original order afterwards.
  • Alternatives. For bigger programs consider getopt_long (as above), argp (glibc only) or a small hand-written loop.