- 论坛徽章:
- 2
|
- #include <string.h>
- #include <stdio.h>
- struct t_option {
- const char *long_name;
- int short_name;
- int phased;
- };
- int f_getopt_long(struct t_option *ops, const char *name) {
- int index;
- index = 0;
- while (ops[index].long_name != NULL) {
- if (!ops[index].phased && strcmp(ops[index].long_name, name) == 0) {
- ops[index].phased = 1;
- return index;
- }
- index++;
- }
- return -1;
- }
- int f_getopt_short(struct t_option *ops, int name) {
- int index;
- index = 0;
- while (ops[index].long_name != NULL) {
- if (!ops[index].phased && ops[index].short_name == name) {
- ops[index].phased = 1;
- return index;
- }
- index++;
- }
- return -1;
- }
- int f_getopt(int argc, const char *argv[], struct t_option *cmds, struct t_option *ops) {
- int index;
- int cmd;
- int retval;
- cmd = -1;
- for (index = 1; index < argc; index++) {
- if (argv[index][0] != '-') {
- break;
- }
- if (argv[index][1] == '-') {
- retval = f_getopt_long(cmds, &argv[index][2]);
- if (retval == -1 && ops != NULL) {
- retval = f_getopt_long(ops, &argv[index][2]);
- }else {
- cmd = retval;
- }
- if (retval == -1) {
- break;
- }
- }
- if (argv[index][2] != '\0') {
- break;
- }
- retval = f_getopt_short(cmds, argv[index][1]);
- if (retval == -1 && ops != NULL) {
- retval = f_getopt_short(ops, argv[index][1]);
- }else {
- cmd = retval;
- }
- if (retval == -1) {
- break;
- }
- }
- return cmd;
- }
- int main(int argc, const char *argv[]) {
- struct t_option cmds[] = {
- "help", 'h', 0,
- "version", 'v', 0,
- "traditional", 't', 0,
- "next_generation", 'n', 0,
- NULL, 0, 0,
- };
- switch (f_getopt(argc, argv, cmds, NULL)) {
- default:
- case 0:
- printf( "``hello'' is a greeting program which wrote by flw.\n"
- "\n"
- "Usage: hello [OPTIONS]\n"
- " -h, --help display this message then exit.\n"
- " -v, --version display version information then exit.\n"
- "\n"
- " -t, --traditional output a greeting message with traditional format.\n"
- " -n, --next-generation output a greeting message with next-generation format.\n"
- "\n"
- "Report bugs to <flw@cpan.org>\n"
- );
- break;
- case 1:
- printf( "hello - flw's hello world. 0.8 version\n" );
- break;
- case 2:
- printf( "hello, world\n" );
- break;
- case 3:
- printf(
- "+---------------+\n"
- "| Hello, world! |\n"
- "+---------------+\n"
- );
- break;
- }
- return 0;
- }
复制代码 |
|