您的位置:首页 > 运维架构

处理命令行参数的函数--getopt_long

2012-04-26 00:00 375 查看
最后知道真相的我眼泪掉下来~~

/**
* demonstrate the usage of getopt_long
*
* getopt_long, optarg, optind
**/
#include <getopt.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

const char* program_name;

/**
* function: print_usage
* @stream : file stream for output
* @exitcode: exit code
*
**/
void print_usage(FILE* stream, int exitcode)
{
fprintf(stream, "Usage: %s options [ inputfile ... ] \n", program_name);
fprintf(stream,
" -h --help Display this usage infomation. \n"
" -o --output filename Write output to file. \n"
" -v --verbose Print verbose messages. \n");
exit(exitcode);
}

int main(int argc, char *argv[])
{
int next_option;

const char* const short_options = "ho:v"; /* the string cannot be modified as well as the pointer */
const struct option long_options[] = {
{"help", 0, NULL, 'h'}, /* --help, no argument for this option, corresponds to -h option */
{"output", 1, NULL, 'o'},
{"verbose", 0, NULL, 'v'},
{NULL, 0, NULL, 0},
};

const char* output_filename = NULL;
int verbose = 0;

/* start parsing options */

program_name = argv[0];
do
{
next_option = getopt_long(argc, argv, short_options, long_options, NULL);
switch (next_option)
{
case 'h':
print_usage(stdout, 0);
break;
case 'o':
output_filename = optarg;
break;
case 'v':
verbose = 1;
break;
case '?':
print_usage(stderr, 1);
case -1: /* done with options */
break;
default: /* something unexpected */
abort();

}
} while (next_option != -1);

if (verbose)
{
int i;
for (i=optind; i<argc; i++)
printf("Argument: %s \n", argv[i]);
}
/* main body of the program */
return 0;
}

root@localhost :/home/James/mypro/ALP/getopt_long# ./demo -dd
./demo: invalid option -- 'd'
Usage: ./demo options [ inputfile ... ]
-h --help Display this usage infomation.
-o --output filename Write output to file.
-v --verbose Print verbose messages.
root@localhost :/home/James/mypro/ALP/getopt_long# ./demo -v -o put input1 input2 input3
Argument: input1
Argument: input2
Argument: input3
root@localhost :/home/James/mypro/ALP/getopt_long# ./demo -h
Usage: ./demo options [ inputfile ... ]
-h --help Display this usage infomation.
-o --output filename Write output to file.
-v --verbose Print verbose messages.
root@localhost :/home/James/mypro/ALP/getopt_long# ./demo -m
./demo: invalid option -- 'm'
Usage: ./demo options [ inputfile ... ]
-h --help Display this usage infomation.
-o --output filename Write output to file.
-v --verbose Print verbose messages.
root@localhost :/home/James/mypro/ALP/getopt_long# ./demo -v input1 input2 input3
Argument: input1
Argument: input2
Argument: input3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: