[How to implement command options? Think of the input parameters argc, argv in the main function]
Course Content#
getopt Function#
【Command Line Parsing Function】
- <unistd.h> → Unix Standard
- ⭐Function Prototype
- int getopt(int argc, char * const argv[], const char *optstring);
- Guess
- Return value int
- ① 0: Success; -1: Failure
- ② ≥0: Success; <0: Failure
- Parameters argc, argv: Similar to the parameters of the main function
- Parameter optstring: Option string
- Return value int
- View man manual: man 3 getopt
- Return value is character [option] or -1
- When returning, it will update the external variable optind and the static variable nextchar
- If there are no options left, return -1, optind moves to the position of the first element of argv [not an option]
- argc, argv
- Directly passed from the main function parameters
- optstring
- Meaning: A string composed of all valid optional characters
- A single character represents an option
- If a single character is followed by a colon
- One colon means that this option must be followed by a parameter value
- The parameter follows immediately after the option or is separated by a space
- [Similar to the existence of option parameter in commands]
- Two colons mean that the parameter after the option is optional
- If there is a parameter, it must follow the option and cannot be separated by a space
- The pointer to the parameter is assigned to optarg [For two colons, defaults to 0←null]
- One colon means that this option must be followed by a parameter value
- Example
- x, y, z represent 3 options
- Repeated calls to getopt() can read multiple options, such as -al -h
- Some global variables
-
- optarg: Can extract option parameters when there is a colon
- optind
- Meaning: Index of the next element [character] in the argv array
- When the caller resets it to 1, it can rescan argv
- [PS] External variable; like a pointer
- Can be used directly [no need to declare], as these variables are already defined in the 【included header file】
- Concept of external variables
-
- Return value is character [option] or -1
Code Demonstration#
getopt#
-
- Learn to use flag, switch
- 【Meaning of colon】 Required/Optional option parameters
- Pay attention to global variables related to getopt, which can be used directly
- exit() can use non-zero values to indicate abnormal exit
- Program Results
-
- For reference
-
Additional Knowledge Points#
Points for Consideration#
Tips#
- ⭐Small Assignment: Implement the ls -al command in C language
- Learn to use flowcharts to clarify ideas, recommended ProcessOn——online flowchart drawing website
-
- Simple flowchart from the dorm ship
-
- Learn to use flowcharts to clarify ideas, recommended ProcessOn——online flowchart drawing website
- When first learning commands, do not focus too much on variations
- In vim, enter to view the structured view of the source code
- Common ctags operations: ctrl + ] to jump to definition, ctrl + o to return