这个程序的代码对于很多linux程序员应该是很熟悉的,仿照linux实现了
命令行参数解析器,所以提供一个框架程序,以后再写类似代码的时候直接在本框架的基础上修改就是了。
- #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;
- }