
 
文章目录
具体实现如下:
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
void print_help(char *argv[]) {  
    printf("Usage: %s [options]\n", argv[0]);  
    printf("Options:\n");  
    printf("  -h, --help       Print this help message\n");  
    printf("  -v, --version     Print version information\n");  
    printf("  -a, --arg         Argument option\n");  
    printf("  -b, --flag        Flag option\n");  
}  
  
int main(int argc, char *argv[]) {  
    int opt;  
    int arg_count = 0;  
    int flag_count = 0;  
  
    while ((opt = getopt(argc, argv, "havb:")) != -1) {  
        switch (opt) {  
            case 'h':  
            case '--help':  
                print_help(argv);  
                exit(EXIT_SUCCESS);  
            case 'v':  
            case '--version':  
                printf("Version: %s\n", VERSION);  
                exit(EXIT_SUCCESS);  
            case 'a':  
            case '--arg':  
                arg_count++;  
                printf("Argument option %d: %s\n", arg_count, optarg);  
                break;  
            case 'b':  
            case '--flag':  
                flag_count++;  
                printf("Flag option %d: %s\n", flag_count, optarg);  
                break;  
            default:  
                printf("Error: Invalid option %c\n", opt);  
                print_help(argv);  
                exit(EXIT_FAILURE);  
        }  
    }  
  
    return 0;  
}
 
在这个示例中,我们使用了 getopt() 函数来解析命令行参数。我们定义了四个选项:-h/–help、-v/–version、-a/–arg 和 -b/–flag。当用户输入 -h 或 --help 时,程序会打印出帮助信息并退出。当用户输入 -v 或 --version 时,程序会打印出版本信息并退出。当用户输入 -a 或 --arg 时,程序会将其视为一个参数选项,并将其打印出来。当用户输入 -b 或 --flag 时,程序会将其视为一个标志选项,并将其打印出来。如果用户输入了无效的选项,程序会打印出错误信息并退出。



















