Home
Main website
Display Sidebar
Hide Ads
Recent Changes
View Source:
getopt(3)
Edit
PageHistory
Diff
Info
LikePages
!!NAME getopt - Parse command line options !!SYNOPSIS __#include <unistd.h>__ __int getopt(int __''argc''__, char * const __''argv''__[],__ __const char *__''optstring''__);__ __extern char *__''optarg''__;__ __extern int __''optind''__, __''opterr''__, __''optopt''__;__ __#define _GNU_SOURCE__ __#include <getopt.h>__ __int getopt_long(int __''argc''__, char * const __''argv''__[],__ __const char *__''optstring''__,__ __const struct option *__''longopts''__, int *__''longindex''__);__ __int getopt_long_only(int __''argc''__, char * const __''argv''__[],__ __const char *__''optstring''__,__ __const struct option *__''longopts''__, int *__''longindex''__);__ !!DESCRIPTION The __getopt()__ function parses the command line arguments. Its arguments ''argc'' and ''argv'' are the argument count and array as passed to the __main()__ function on program invocation. An element of ''argv'' that starts with `-' (and is not exactly ''getopt()__ is called repeatedly, it returns successively each of the option characters from each of the option elements. If __getopt()__ finds another option character, it returns that character, updating the external variable ''optind'' and a static variable ''nextchar'' so that the next call to __getopt()__ can resume the scan with the following option character or ''argv''-element. If there are no more option characters, __getopt()__ returns -1. Then ''optind'' is the index in ''argv'' of the first ''argv''-element that is not an option. ''optstring'' is a string containing the legitimate option characters. If such a character is followed by a colon, the option requires an argument, so __getopt__ places a pointer to the following text in the same ''argv''-element, or the text of the following ''argv''-element, in ''optarg''. Two colons mean an option takes an optional arg; if there is text in the current ''argv''-element, it is returned in ''optarg'', otherwise ''optarg'' is set to zero. This is a GNU extension. If ''optstring'' contains __W__ followed by a semicolon, then __-W foo__ is treated as the long option __--foo__. (The __-W__ option is reserved by POSIX.2 for implementation extensions.) This behaviour is a GNU extension, not available with libraries before GNU libc 2. By default, __getopt()__ permutes the contents of ''argv'' as it scans, so that eventually all the non-options are at the end. Two other modes are also implemented. If the first character of ''optstring'' is `+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered. If the first character of ''optstring'' is `-', then each non-option ''argv''-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other ''argv''-elements in any order and that care about the ordering of the two.) The special argument `--' forces an end of option-scanning regardless of the scanning mode. If __getopt()__ does not recognize an option character, it prints an error message to stderr, stores the character in ''optopt'', and returns `?'. The calling program may prevent the error message by setting ''opterr'' to 0. The __getopt_long()__ function works like __getopt()__ except that it also accepts long options, started out by two dashes. Long option names may be abbreviated if the abbreviation is unique or is an exact match for some defined option. A long option may take a parameter, of the form __--arg=param__ or __--arg param__. ''longopts'' is a pointer to the first element of an array of __struct option__ declared in ____ as struct option { const char *name; int has_arg; int *flag; int val; }; The meanings of the different fields are: ''name'' is the name of the long option. ''has_arg'' is: __no_argument__ (or 0) if the option does not take an argument, __required_argument__ (or 1) if the option requires an argument, or __optional_argument__ (or 2) if the option takes an optional argument. ''flag'' specifies how results are returned for a long option. If ''flag'' is __NULL__, then __getopt_long()__ returns ''val''. (For example, the calling program may set ''val'' to the equivalent short option character.) Otherwise, __getopt_long()__ returns 0, and ''flag'' points to a variable which is set to ''val'' if the option is found, but left unchanged if the option is not found. ''val'' is the value to return, or to load into the variable pointed to by ''flag''. The last element of the array has to be filled with zeroes. If ''longindex'' is not __NULL__, it points to a variable which is set to the index of the long option relative to ''longopts''. __getopt_long_only()__ is like __getopt_long()__, but `-' as well as `--' can indicate a long option. If an option that starts with `-' (not `--') doesn't match a long option, but does match a short option, it is parsed as a short option instead. !!RETURN VALUE The __getopt()__ function returns the option character if the option was found successfully, `:' if there was a missing parameter for one of the options, `?' for an unknown option character, or -1 for the end of the option list. __getopt_long()__ and __getopt_long_only()__ also return the option character when a short option is recognized. For a long option, they return ''val'' if ''flag'' is __NULL__, and 0 otherwise. Error and -1 returns are the same as for __getopt()__, plus `?' for an ambiguous match or an extraneous parameter. !!ENVIRONMENT VARIABLES __POSIXLY_CORRECT__ If this is set, then option processing stops as soon as a non-option argument is encountered. ___<PID>_GNU_nonoption_argv_flags___ This variable was used by __bash__ 2.0 to communicate to GNU libc which arguments are the results of wildcard expansion and so should not be considered as options. This behaviour was removed in __bash__ version 2.01, but the support remains in GNU libc. !!EXAMPLE The following example program illustrates the use of __getopt_long()__ with most of its features. #include <stdio.h> /* for printf */ #include <stdlib.h> /* for exit */ #include <getopt.h> int main (int argc, char **argv) { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; int option_index = 0; static struct option long_options[] = { {"add", 1, 0, 0}, {"append", 0, 0, 0}, {"delete", 1, 0, 0}, {"verbose", 0, 0, 0}, {"create", 1, 0, 'c'}, {"file", 1, 0, 0}, {0, 0, 0, 0} }; c = getopt_long (argc, argv, "abc:d:012", long_options, &option_index); if (c == -1) break; switch (c) { case 0: printf ("option %s", long_options[[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\n"); break; case '0': case '1': case '2': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case 'd': printf ("option d with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[[optind++]); printf ("\n"); } exit (0); } An short and sweet example of getopt usage: int ch; /* Butchered out of [tcpperf|http://www.wand.net.nz/~stj2/nsc/software.html] by SamJansen */ while ((ch = getopt(argc, argv, "c:p:s:")) != -1) switch (ch) { case 'c': /* Client machine to connect to */ client = optarg; break; case 'p': /* port */ port = atoi(optarg); break; case 's': write_size = atoi(optarg); break; case '?': default: usage(argv[[0]); } argc -= optind; argv += optind; !!BUGS The [POSIX].2 specification of __getopt()__ has a technical error described in POSIX.2 Interpretation 150. The GNU implementation (and probably all other implementations) implements the correct behaviour rather than that specified. !!CONFORMING TO __getopt()__: [POSIX].2, provided the environment variable [POSIXLY_CORRECT] is set. Otherwise, the elements of ''argv'' aren't really const, because we permute them. We pretend they're const in the prototype to be compatible with other systems. ---- !NOTES ! getopt keeps internal state If you want to use getopt more than once within a program, across different inputs, you'll need to reset its internal state counters before each use: <pre> printf("%d %d %d\n",optind,opterr,optopt); ... do getopt stuff ... printf("%d %d %d\n",optind,opterr,optopt); </pre> This outputs the following: <pre> 1 1 63 3 1 63 </pre> the '3' in my case is because I only had one option + parameter (+ program name == 3). So, if you reset optind, opterr and optopt to 1, 1 and 63, before each new use of getopt, you should be fine. -- DanielLawson
4 pages link to
getopt(3)
:
Man3g
ash(1)
POSIXLY_CORRECT
getopt(1)
This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.