使用的是关键的函数getopt_long
- #include <unistd.h>
- int getopt(int argc, char * const argv[],
- const char *optstring);
- extern char *optarg;
- extern int optind, opterr, optopt;
- #include <getopt.h>
- int getopt_long(int argc, char * const argv[],
- const char *optstring,
- const struct option *longopts, int *longindex);
- int getopt_long_only(int argc, char * const argv[],
- const char *optstring,
- const struct option *longopts, int *longindex);
-
- #include "GetOpt.h"
- #include<iostream>
- using namespace std;
- const char* program_name;
- void print_usage ()
- {
- cout << "Usage: %s options [outputfile ...]" << endl;
- cout << " -h --help Display this usage information." << endl;
- cout << " -o --output filename Write output to file." << endl;
- cout << " -v --verbose Print verbose messages." << endl;
- }
- int main (int argc, char* argv[])
- {
- int opt;
- const char* const short_options = "ho:v";
- const struct option long_options[] = {
- { "help", no_argument, NULL, 'h' },
- { "output", required_argument, NULL, 'o' },
- { "verbose", no_argument, NULL, 'v' },
- { NULL, no_argument, NULL, 0 }
- };
- int verbose = 0;
- program_name = argv[0];
- opt = getopt_long (argc, argv, short_options,long_options, NULL);
- if(opt == -1)
- {
- print_usage();
- exit(0);
- }
- while(opt != -1)
- {
- switch (opt)
- {
- case 'o':
- cout << "outputfile is: " << optarg << endl;
- break;
- case 'v':
- cout << "print verbose infomation" << endl;
- break;
- case '?':
- cout << "sytax error: no this argument: " << static_cast<char>(optopt) << endl;
- print_usage();
- exit(0);
- case 'h':
- print_usage ();
- break;
- default:
- break;
- }
- opt = getopt_long (argc, argv, short_options,long_options, NULL);
- }
- return 0;
- }
本文详细介绍了使用getopt_long函数处理命令行参数的方法,包括其核心函数的用法、参数解释及实例应用。通过具体代码示例,展示了如何灵活运用getopt_long实现复杂命令行参数的解析。
308

被折叠的 条评论
为什么被折叠?



