GNU/Linux C language: Command Options Parsing

1.GNU/Linux Command-Line Conventions

Almost all GNU/Linux programs obey some conventions about how command-line arguments are interpreted.The arguments that programs expect fall into two categories:options(orflags) and other arguments. Options modify how the program behaves, while other arguments provide inputs (for instance, the names of input files).

Options come in two forms:

Short optionsconsist of a single hyphen and a single character (usually a lowercase or uppercase letter). Short options are quicker to type.

Long optionsconsist of two hyphens, followed by a name made of lowercase and uppercase letters and hyphens. Long options are easier to remember and easier to read (in shell scripts, for instance).

Usually, a program provides both a short form and a long form for most options it supports, the former for brevity and the latter for clarity. For example, most programs understand the options-hand--help, and treat them identically. Normally, when a program is invoked from the shell, any desired options follow the program name immediately. Some options expect an argument immediately following. Many programs, for example, interpret the option--output footo specify that output of the program should be placed in a file namedfoo. After the options, there may follow other command-line arguments, typically input files or input data.

For example, the commandls -s /displays the contents of the root directory.The-soption modifies the default behavior oflsby instructing it to display the size (in kilobytes) of each entry.The/argument tellslswhich directory to list.The--sizeoption is synonymous with-s, so the same command could have been invoked asls --size /.

TheGNU Coding Standardslist the names of some commonly used command-line options. If you plan to provide any options similar to these, it’s a good idea to use the names specified in the coding standards.Your program will behave more like other programs and will be easier for users to learn.

2.Usinggetopt_long

Parsing command-line options is a tedious chore. Luckily, the GNU C library provides a function that you can use in C and C++ programs to make this job somewhat easier (although still a bit annoying).This function,getopt_long, understands both short and long options. If you use this function, include the header file.

Suppose, for example, that you are writing a program that is to accept the three options shown in Table 2.1.

Table 2.1Example Program Options

**Short Form** **Long Form** **Purpose**
-h --help Display usage summary and exit
-o filename --outputfilename Specify output filename
-v --verbose Print verbose messages

In addition, the program is to accept zero or more additional command-line arguments, which are the names of input files.

To usegetopt_long, you must provide two data structures.The first is a character string containing the valid short options, each a single letter. An option that requires an argument is followed by a colon. For your program, the stringho:vindicates that the valid options are-h,-o, and-v, with the second of these options followed by an argument.

To specify the available long options, you construct an array ofstruct optionelements. Each element corresponds to one long option and has four fields. In normal circumstances, the first field is the name of the long option (as a character string, without the two hyphens); the second is 1 if the option takes an argument, or 0 otherwise; the third isNULL; and the fourth is a character constant specifying the short option synonym for that long option.The last element of the array should be all zeros.You could construct the array like this:

**const****struct**option long_options[] ={

{"help", 0, NULL,'h'},

{"output", 1, NULL,'o'},

{"verbose", 0, NULL,'v'},

{NULL, 0, NULL, 0}

};

You invoke thegetopt_longfunction, passing it theargcandargvarguments tomain, the character string describing short options, and the array ofstruct optionelements describing the long options.

Each time you callgetopt_long, it parses a single option, returning the shortoption letter for that option, or –1 if no more options are found.

Typically, you’ll callgetopt_longin a loop, to process all the options the user has specified, and you’ll handle the specific options in a switch statement.

Ifgetopt_longencounters an invalid option (an option that you didn’t specify as a valid short or long option), it prints an error message and returns the character?(a question mark). Most programs will exit in response to this, possibly after displaying usage information.

When handling an option that takes an argument, the global variableoptargpoints to the text of that argument.

Aftergetopt_longhas finished parsing all the options, the global variableoptindcontains the index (intoargv) of the first nonoption argument. Listing 2.2 shows an example of how you might usegetopt_longto process your arguments.

Listing 2.2(getopt_long.c) Usinggetopt_long

**#include**

**#include**

**#include**

/* The name of this program. */

**const****char*** program_name;

/* Prints usage information for this program to STREAM (typically

stdout or stderr), and exit the program with EXIT_CODE. Does not

return. */

**void****print_usage**(FILE* stream,**int**exit_code) {

**fprintf**(stream,"Usage: %s options [ inputfile ... ]\n", program_name);

**fprintf**(stream," -h --help Display this usage information.\n"

" -o --output filename Write output to file.\n"

" -v --verbose Print verbose messages.\n");

**exit**(exit_code);

}

/* Main program entry point. ARGC contains number of argument list

elements; ARGV is an array of pointers to them. */

**int****main**(**int**argc,**char*** argv[]) {

**int**next_option;

/* A string listing valid short options letters. */

**const****char*****const**short_options ="ho:v";

/* An array describing valid long options. */

**const****struct**option long_options[] = { {"help", 0, NULL,'h'}, {

"output", 1, NULL,'o'}, {"verbose", 0, NULL,'v'}, { NULL, 0,

NULL, 0 }/* Required at end of array. */

};

/* The name of the file to receive program output, or NULL for

standard output. */

**const****char*** output_filename = NULL;

/* Whether to display verbose messages. */

**int**verbose = 0;

/* Remember the name of the program, to incorporate in messages.

The name is stored in argv[0]. */

program_name = argv[0];

**do**{

next_option

=**getopt_long**(argc, argv, short_options, long_options, NULL);

**switch**(next_option) {

**case**'h':/* -h or --help */

/* User has requested usage information. Print it to standard

output, and exit with exit code zero (normal termination). */

print_usage(stdout, 0);

**case**'o':/* -o or --output */

/* This option takes an argument, the name of the output file. */

output_filename = optarg;

**break**;

**case**'v':/* -v or --verbose */

verbose = 1;

**break**;

**case**'?':/* The user specified an invalid option. */

/* Print usage information to standard error, and exit with exit

code one (indicating abnormal termination). */

print_usage(stderr, 1);

**case**-1:/* Done with options. */

**break**;

**default**:/* Something else: unexpected. */

**abort**();

}

}**while**(next_option != -1);

/* Done with options. OPTIND points to first nonoption argument.

For demonstration purposes, print them if the verbose option was

specified. */

**if**(verbose) {

**int**i;

**for**(i = optind; i < argc; ++i)

**printf**("Argument: %s\n", argv[i]);

}

/* The main program goes here. */

**return**0;

}

Usinggetopt_longmay seem like a lot of work, but writing code to parse the command-line options yourself would take even longer.Thegetopt_longfunction is very sophisticated and allows great flexibility in specifying what kind of options to accept. However, it’s a good idea to stay away from the more advanced features and stick with the basic option structure described.
原文链接: https://www.cnblogs.com/MagicLetters/archive/2010/09/24/1834115.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/15421

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午3:20
下一篇 2023年2月7日 下午3:22

相关推荐