The Climate and City 遍历linux的环境变量
Jan 06

1. 包含getopt.h
2. 定义短选项,比如,ho:v
3. 定义长选项结构,注意最后一项全部设为0
4. 未定义的选项,解析时会返回’?’
5. 含有参数的选项,参数存于全局变量optarg中
6. 非参数选项的起始索引,存于全局变量optind中

示例程序如下:

#include <stdlib.h></stdlib.h>
#include <stdio.h></stdio.h>
#include <getopt.h></getopt.h>

const char* program_name;

void print_usage(FILE* stream, int exit_code){
        fprintf(stream, "Usage: %s options [ inputfile ...]n", program_name);
        fprintf(stream, "    -h   –help        Display this uage information.n"
                        "    -v   –verbose     Print verbose message.n"
                        "    -o   –output filename    Write output to file.n");
        exit(exit_code);
}

int main(int argc, char* argv[]){
        int next_option;
        const char* short_options = "ho:v";
        const struct option long_options[] = {
                {"help", 0, NULL, ‘h’},
                {"output", 1, NULL, ‘o’},
                {"verbose", 0, NULL, ‘v’},
                {NULL, 0, NULL, 0}
                };
        const char* output_filename = NULL;
        int verbose = 0;
        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);
                        case ‘o’:
                                //the global var optarg contains the specified argument
                                output_filename = optarg;
                                break;
                        case ‘v’:
                                verbose = 1;
                                break;
                        case ‘?’: //if the arg list contains invalid options
                                print_usage(stderr, 1);
                        case -1:
                                break;
                        default:
                                abort();
                }
        }while(next_option != -1);
        printf("[option] verbose: %dn", verbose);
        printf("[option] output: %sn", output_filename);
        if(verbose){
                int i;
                //the global var optind contains the index of the first nonoption argument
                for(i = optind; i<argc;></argc;>                        printf("Argument: %sn", argv[i]);
                }
        }
        return 0;
}

相应的Makefile:

CC=g++
CFLAGS=-Wall -g

all: getopt

getopt: getopt.o
        $(CC) $(CFLAGS) -o $@ $@.o

%.o: %.c
        $(CC) $(CFLAGS) -c $+

clean:
        rm -f *.o
        rm -f getopt

随机日志

Leave a Reply