Detailed getopt

 

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

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

Function Description:

  Function is used to parse commands, options, parameters,

cmd -option arg

  '-' followed by a later option, the option may be parameters.

  argc, argv for transmitting command information.

  optstring used to specify the list of options, there are two ways to specify

optstring = "xp"
optstring = "x:p:"

  The former represents the options are x, p, no arguments, which represents the options are x, p, and has parameters.

  When using the latter optstring, word after the option is treated as parameters, such as:

a.out -x -p

  Here "-p" are treated as arguments to -x.

  The function returns an int, checking to return the option character when successful, failed to return -1 (indicates the transmission of information checked and did not find the option).

  By calling this function repeatedly, until the returns -1, process all the options to transfer information.

 

  Global variables:

    optarg, when they are found option, optarg be accused parameters to the options.

    optind, is initialized to 1, the index indicates the input information is to be checked, when the option is found, after optind shift, as follows:

// When optstring = "x: p", i.e. the option parameters 
./a.out -x 123 -p

    The above case, the first call to getopt, find the x option, optind after being shifted by optind == 1 change to optind == 3

// When optstring = "xp" i.e. without parameters 
./a.out -x -p

    Above, the first call to getopt, find the x option, optind after being shifted by optind == 1 change to optind == 2

    As can be seen, is OPTIND the argv array index, is expected to point to the next location options.

    opterr for inhibiting the error message displayed by the printing getopt (), which is a default variable, it can be set to 0 to disable the error message is printed.

    optopt information for pointing errors, such as

//optstring = "x:p:"
./a.out -x

    -x After the required parameters, but not, optopt to store the character 'x'

//optstring = "xp"
./a.out a

    'A' is not an option character, optopt store the error character.

 

return value:

    Normally, getopt returns the option character found.

    If the input character is not an option character, it returns '?'

    If the option character with arguments, but no input parameters, return ':'

    Back to -1:

      (1) argv traverse over, i.e. argv [optind] == NULL

      (2) argv [optind] [0] =! '-' input options i.e. x

      (3) does not enter the correct option. 

 

The sample program:

/*************************************************************************\
*                  Copyright (C) Michael Kerrisk, 2019.                   *
*                                                                         *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the   *
* Free Software Foundation, either version 3 or (at your option) any      *
* later version. This program is distributed without any warranty.  See   *
* the file COPYING.gpl-v3 for details.                                    *
\*************************************************************************/

/* Listing B-1 */

#include <ctype.h>
#include "tlpi_hdr.h"

#define printable(ch) (isprint((unsigned char) ch) ? ch : '#')

static void             /* Print "usage" message and exit */
usageError(char *progName, char *msg, int opt)
{
    if (msg != NULL && opt != 0)
        fprintf(stderr, "%s (-%c)\n", msg, printable(opt));
    fprintf(stderr, "Usage: %s [-p arg] [-x]\n", progName);
    exit(EXIT_FAILURE);
}

int
main(int argc, char *argv[])
{
    int opt, xfnd;
    char *pstr;

    xfnd = 0;
    pstr = NULL;

    while ((opt = getopt(argc, argv, ":p:x")) != -1) {
        printf("opt =%3d (%c); optind = %d", opt, printable(opt), optind);
        if (opt == '?' || opt == ':')
            printf("; optopt =%3d (%c)", optopt, printable(optopt));
        printf("\n");

        switch (opt) {
        case 'p': pstr = optarg;        break;
        case 'x': xfnd++;               break;
        case ':': usageError(argv[0], "Missing argument", optopt);
        case '?': usageError(argv[0], "Unrecognized option", optopt);
        default:  fatal("Unexpected case in switch()");
        }
    }

    if (xfnd != 0)
        printf("-x was specified (count=%d)\n", xfnd);
    if (pstr != NULL)
        printf("-p was specified with the value \"%s\"\n", pstr);
    if (optind < argc)
        printf("First nonoption argument is \"%s\" at argv[%d]\n",
                argv[optind], optind);
    exit(EXIT_SUCCESS);
}

  

Guess you like

Origin www.cnblogs.com/yangxinrui/p/11409157.html