Getopt function usage and getopt function usage
Linux provides a function to parse command line parameters.
#include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt;
Using this function, we can run the following command:
./a.out -n -t 100
N does not require a parameter. t requires a value as a parameter.
The Code is as follows:
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <errno.h>#define ERR_EXIT(m) \ do { \ perror(m);\ exit(EXIT_FAILURE);\ }while(0)int main(int argc, char *argv[]){ int opt; while(1) { opt = getopt(argc, argv, "nt:"); if(opt == '?') exit(EXIT_FAILURE); if(opt == -1) break; switch(opt) { case 'n': printf("AAAAAAAA\n"); break; case 't': printf("BBBBBBBB\n"); int n = atoi(optarg); printf("n = %d\n", n); } } return 0;}
If an invalid parameter is input, getopt returns '? ', When the resolution is complete,-1 is returned.
If a parameter is required, use optarg to obtain it. This is a global variable.
Note that the third parameter "nt:" Of getopt indicates that n and t are available, and t is followed by a colon, indicating that t requires additional parameters.
The running result is as follows:
5:30:22 wing@ubuntu msg ./getopt_test -nAAAAAAAA5:30:26 wing@ubuntu msg ./getopt_test -t ./getopt_test: option requires an argument -- 't'5:30:31 wing@ubuntu msg ./getopt_test -t 100 1 ↵BBBBBBBBn = 100