Welcome, guest | Sign In | My Account | Store | Cart

working with getopt

C, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
static int getargs(int argc, char **argv)
{
    int opt = 0;

    char *optstring = "acdh";

    opt = getopt(argc, argv, optstring);

    while (opt != -1) {
        switch (opt) {
            case 'a':
                printf("all\n");
                break;
            case 'c':
                printf("confirm\n");
                break;
            case 'd':
                printf("delete\n");
                break;
            case 'h':
                printf("help\n");
                break;
            default:
                printf("other %s\n", optstring);
                break;
        }
        opt = getopt(argc, argv, optstring);
    }

    printf("non-options\n");
    while( optind < argc ){
        printf("%s\n", argv[optind]);
        optind++;
    }
    return 0;
}

An element of argv that starts with '-' (and is not exactly "-" or "--") is an option element.

The characters of this element (aside from the initial '-') are option characters. If 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.

By default, getopt() permutes the contents of argv as it scans, so that eventually all the non-options are at the end.

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. 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.

1 comment

J Y (author) 14 years, 6 months ago  # | flag

snprintf(ar_user, sizeof(ar_user), "%s", optarg);

Created by J Y on Wed, 20 May 2009 (MIT)
C recipes (32)
J Y's recipes (21)

Required Modules

  • (none specified)

Other Information and Tasks