C/C++ 命令解析:getopt 方法详解和使用示例

本文介绍了getopt()方法的使用,包括参数解析、实例演示及如何处理不同类型的输入参数。通过几个具体的实例,读者可以深入了解getopt方法的工作原理及其在命令行参数处理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介

getopt() 方法是用来分析命令行参数的,该方法由 Unix 标准库提供,包含在 <unistd.h> 头文件中。

二、定义

int getopt(int argc, char * const argv[], const char *optstring);
 
extern char *optarg;
extern int optind, opterr, optopt;

getopt 参数说明:

  • argc:通常由 main 函数直接传入,表示参数的数量
  • argv:通常也由 main 函数直接传入,表示参数的字符串变量数组
  • optstring:一个包含正确的参数选项字符串,用于参数的解析。例如 “abc:”,其中 -a,-b 就表示两个普通选项,-c 表示一个必须有参数的选项,因为它后面有一个冒号

外部变量说明:

  • optarg:如果某个选项有参数,这包含当前选项的参数字符串
  • optind:argv 的当前索引值
  • opterr:正常运行状态下为 0。非零时表示存在无效选项或者缺少选项参数,并输出其错误信息
  • optopt:当发现无效选项字符时,即 getopt() 方法返回 ? 字符,optopt 中包含的就是发现的无效选项字符

三、实例分析

让我们通过一系列的实例来掌握 getopt 方法的使用吧。

1. 简单实例

OptDemo.c 如下:

#include <stdio.h>
#include <unistd.h>
 
int main(int argc, char *argv[]) {
    int o;
    const char *optstring = "abc:"; // 有三个选项-abc,其中c选项后有冒号,所以后面必须有参数
    while ((o = getopt(argc, argv, optstring)) != -1) {
        switch (o) {
            case 'a':
                printf("opt is a, oprarg is: %s\n", optarg);
                break;
            case 'b':
                printf("opt is b, oprarg is: %s\n", optarg);
                break;
            case 'c':
                printf("opt is c, oprarg is: %s\n", optarg);
                break;
            case '?':
                printf("error optopt: %c\n", optopt);
                printf("error opterr: %d\n", opterr);
                break;
        }
    }
    return 0;
}

编译和运行:

分析:

命令 gcc OptDemo.c -o OptDemo 是使用 gcc 把 OptDemo.c 编译成可执行程序,命名为 OptDemo

第一次运行 ./OptDemo -a -b -c afei 正常执行和输出

第二次运行 ./OptDemo -abc 由于选项 c 后没有输入参数,于是报错

第三次运行 ./OptDemo -d 由于选项 d 不是我们在 optstring 中预定义的选项,于是报错

2. 可选参数

一个冒号表示选项后必须有参数,没有参数就会报错。如果有两个冒号的话,那么这个参数就是可选参数了,即可有可没有。
OptDemo.c 如下:

#include <stdio.h>
#include <unistd.h>
 
void usage() {
    printf("Usage:\n");
    printf("\tOptDemo [-a] [-b] [-c message]");
}
 
int main(int argc, char *argv[]) {
    int o;
    const char *optstring = "abc::"; // 有三个选项-abc,其中c选项后有两个冒号,表示后面可选参数
    while ((o = getopt(argc, argv, optstring)) != -1) {
        switch (o) {
            case 'a':
                printf("opt is a, oprarg is: %s\n", optarg);
                break;
            case 'b':
                printf("opt is b, oprarg is: %s\n", optarg);
                break;
            case 'c':
                printf("opt is c, oprarg is: %s\n", optarg);
                break;
            case '?':
                printf("发生错误时提示用户正确的使用方式\n");
                usage(); // 提示使用说明
                break;
        }
    }
    return 0;
}

编译和运行:

分析:

注意这里 可选参数 选项 -c 后面跟参数的时候,一定不能有空格。

但是如果是 必选参数,即选项后面只有一个冒号,则是有没有空格都可以。

3. 输入字符串转 int

由于 optarg 都是字符串类型的,所以当我们想要整型的输入参数时,会经常用到 atio() 这个方法,这里也简单介绍一下。
atoi (表示 ascii to integer) 是把字符串转换成整型数的一个函数,包含在 <stdlib.h> 头文件中,使用方式如下:

int num = atoi(optarg);

四、扩展长选项

因为挺多人提到这个,还是补充一下把,主要是使用 getopt_long 来扩展。

示例代码:

// 定义长选项结构体数组
static struct option long_options[] = {
	{"verbose", no_argument, 0, 'v'},       // --verbose 对应短选项 -v
	{"input", required_argument, 0, 'i'},   // --input 对应短选项 -i
	{"output", required_argument, 0, 'o'},  // --output 对应短选项 -o
	{"model", required_argument, 0, 'm'},   // --model 对应短选项 -m
	{"height", required_argument, 0, 'h'},  // --height 对应短选项 -h
	{"width", required_argument, 0, 'w'},   // --width 对应短选项 -w
	{0, 0, 0, 0}                            // 必须用全零填充结束
};
int opt;
int option_index = 0;
bool verbose = false;
std::string input_file;
std::string output_file;
std::string model_file;
int image_height;
int image_width;

// 解析选项(支持短选项和长选项)
while ((opt = getopt_long(argc, argv, "vi:o:m:h:w:", long_options, &option_index)) != -1) {
	switch (opt) {
		case 'v':
			verbose = true;  // -v 或 --verbose
			break;
		case 'i':
			input_file = optarg;  // -i <参数> 或 --input=<参数>‌
			break;
		case 'o':
			output_file = optarg;  // -o <参数> 或 --output=<参数>
			break;
		case 'm':
			model_file = optarg;  // -m <参数> 或 --model=<参数>
			break;
		case 'h':
			image_height = atoi(optarg);  // -h <参数> 或 --height=<参数>
			break;
		case 'w':
			image_width = atoi(optarg);  // -w <参数> 或 --width=<参数>
			break;
		case '?':  // 处理无效选项或缺失参数
			return 1;
		default:
			abort();
	}
}

大部分使用方式还是和之前介绍的一致。

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值