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.
#include <unistd.h> int opt; while ((opt = getopt(argc, argv, "vo:")) != -1) { /* opt is 'v', 'o' (optarg set) or '?' for an error */ }
Try it
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.
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
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.
getoptkeeps its position in global variables, so it is not thread-safe and cannot parse two command lines at once. Resetoptindbefore reusing it. - Argument permutation. glibc moves operands to the end, so
tool file -vstill sees-v. POSIX behavior stops at the first operand; setPOSIXLY_CORRECTor beginoptstringwith+to get it. BSD and macOS stop at the first operand. --ends option processing; everything after it is an operand.- Grouped options.
-vo out.txtis the same as-v -o out.txt, and-oout.txtalso works. - Validate arguments.
optargis just a string; convert numbers withstrtoland check for errors. - Messages. By default
getoptprints a message tostderrfor an unknown option. Library code or tools with their own style should setopterr = 0. mainchanged argv? The array ischar *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.
Related
- fn-main: main and its arguments
- strtol for number options and exit for failure codes
- unistd.h
- Tutorial: Command-line arguments