Command Line Parameter Parsing (1)

Source: Internet
Author: User
Tags arabic numbers posix

When I was reading the code today, I met the getopt_long function and checked the relevant information. It is the parameter parsing of the command line. I will take some notes today.

In Linux, many programs, even those with graphical user interfaces (guis), can accept and process command line options. For some programs, this is the main means to interact with other programs or users. With a reliable and complex command line parameter processing mechanism, your applications will be better and more useful. However, many developers spend their precious time writing their own command line Resolvers without using getopt (), the latter is a library function specifically designed to reduce the burden on command line processing.

1. Command Line Parameters
The primary task of the command line program design is to parse the command line parameters, which is seldom concerned by GUI programmers. Here, we use a popular definition of the parameter (argument): strings on the command line except the command name. Parameters are composed of multiple items. items and items are separated by blank spaces.
Parameters are further divided into options and operands. Option is used to modify the default behavior of a program or provide information for the program. The old Convention begins with a dash. Options can follow some parameters, called option parameters. The rest is the operand.

2. POSIX conventions POSIX indicates portable operating system interfaces: portable operating system interfaces, the Institute of Electrical and Electronics Engineers (IEEE) initially developed POSIX standards, to improve the portability of applications in UNIX environments. However, POSIX is not limited to Unix. Many other operating systems, such as DEC OpenVMS and Microsoft Windows NT, support the POSIX standard.

The following are the conventions on program names and parameters in POSIX:
The program name should not be less than 2 Characters and no more than 9 characters;
The program name should only contain lowercase letters and Arabic numbers;
The option name should be a single-character active single-digit, with a short horizontal '-' as the front digit;
You can merge multiple options that do not require option parameters. (For example, foo-a-B-c ----> foo-ABC)
Options and their parameters are separated by a blank space character;
Optional.
If the option parameter has multiple values, it must be passed in without a string. For example, myprog-U "Arnold, Joe, Jane ". In this case, you need to solve the separation problem of these parameters by yourself.
The option should appear before the operand appears.
The special parameter '--' indicates that all parameters are completed, and any subsequent parameter is considered as the operand.
There is no relationship between options, but they are mutually exclusive. If the operation result of one option overwrites the operation result of other options, the last option takes effect. If the option is repeated, it is processed sequentially.
The sequence of allowed operands affects program behavior, but it must be documented.
The program that reads and writes a specified file should treat a single parameter '-' as a meaningful standard input or output.
Of course, many standards do not comply with the above conventions, mainly due to historical compatibility issues, because before the emergence of the standard, there have been more than n programs.

3. GNU Long Options
GNU encourages programmers to use long options in the form of -- help and -- verbose. These options do not conflict with POSIX conventions, but are easy to remember. They also provide the opportunity to maintain consistency among all GNU tools. The GNU long option has its own conventions:
For GNU programs that have followed the POSIX conventions, each short option has a corresponding long option.
Additional Long Options for GNU do not need the corresponding short options. We recommend that you have them.
The length option can be abbreviated as a string with the minimum uniqueness.
The option parameter and the long option are separated by a '=' or by a blank character.
The option parameter is optional (only valid for the short option ).
The length option can be prefixed with a dash.

4. Basic command line Processing Technology
The C program accesses its command line parameters through the argc and argv parameters. Argc is an integer that represents the number of parameters (including the command name ). The main () function can be defined in two ways. The difference lies only in how argv is defined:

  1. Int main (INT argc, char ** argv)
  2. {
  3. .....
  4. Return 0;
  5. }
  6. Int main (INT argc, char * argv [])
  7. {
  8. .....
  9. Return 0;
  10. }

When the C Runtime Library program starts code to call your main (), the command line has been processed. The argc parameter contains the Count value of the parameter, and argv contains an array of pointers to these parameters. Argv [0] is the program name.

5. Command Line Parameter Parsing function --Getopt ()

The getopt () function declaration is as follows: # include <unistd. h>

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

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

The argc and argv parameters of this function are usually directly transmitted from the main () parameters. Optstring is a string consisting of option letters. If any character in the string is followed by a colon, this option requires an option parameter.

Given the number of getopt () command parameters (argc), the array pointing to these parameters (argv), and the option string (optstring), getopt () returns the first option, and set some global variables. When you call this function again with the same parameters, it returns the next option and sets the corresponding global variable. If no recognizable option is available,-1 is returned, and the task is completed.

The global variables set by getopt () include:
Char * optarg-- Current option parameter string (if any ).
Int optind-- The current index value of argv. When getopt () is used in a while loop, after the loop ends, the remaining strings are treated as operands, which can be found in argv [optind] To argv [argc-1.
Int opterr-- If this variable is not zero, the getopt () function is "invalid option" and "Parameter options are missing, and the error message is output.
Int optopt-- If an invalid option character is found, the getopt () function or '? 'Character, or return ':' character, and optopt contains the found invalid option characters.

The following describes how to use getopt () to write a small program.

Program description:

Program name: opt_parse_demo

Option:
-N -- display my name.
-G -- display my girlfriend's name.
-L -- options with parameters.

  1. # Include <stdio. h>
  2. # Include <unistd. h>
  3. Int main (INT argc, char ** argv)
  4. {
  5. Int OC;/* option character */
  6. Char * B _opt_arg;/* option parameter string */
  7. While (OC = getopt (argc, argv, "NGL :"))! =-1)
  8. {
  9. Switch (OC)
  10. {
  11. Case 'N ':
  12. Printf ("My name is lyong./N ");
  13. Break;
  14. Case 'G ':
  15. Printf ("Her name is xxiong./N ");
  16. Break;
  17. Case 'l ':
  18. B _opt_arg = optarg;
  19. Printf ("Our love is % s/n", optarg );
  20. Break;
  21. }
  22. }
  23. Return 0;
  24. }
  25. Running result: $./opt_parse_demo-n
  26. My name is lyong.
  27. $./Opt_parse_demo-G
  28. Her name is xxiong.
  29. $./Opt_parse_demo-l forever
  30. Our love is forever
  31. $./Opt_parse_demo-NGL forever
  32. My name is lyong.
  33. Her name is xxiong.
  34. Our love is forever

Next, we will introduce the application and examples of functions such as getopt_long.

~~ End ~~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.