Linux C之getopt_long()函数

本文介绍了Linux C编程中getopt_long()函数的用法,主要用于解析命令行参数,支持长选项。在Ubuntu 16.04环境下,该函数原型被展示,并详细解释了参数含义。通过示例和man手册中的例子,展示了如何正确使用该函数,包括处理不同类型的选项参数。

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

该函数遇见位置:V4L2官网中的capture.c文件;

1.函数作用:解析命令行参数,支持长选项,如--device=/dev/video0;

   Ubuntu16.04下getopt_long()函数原型:

NAME
       getopt, getopt_long, getopt_long_only, optarg, optind, opterr, optopt - Parse command-line options

SYNOPSIS
       #include <unistd.h>

       int getopt(int argc, char * const argv[],
                  const char *optstring);

       extern char *optarg;
       extern int optind, opterr, optopt;

       #include <getopt.h>

       int getopt_long(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts, int *longindex);

       int getopt_long_only(int argc, char * const argv[],
                  const char *optstring,
                  const struct option *longopts, int *longindex);

2.参数说明:

argc:传入的参数个数;

argv:传入的参数数组;

optstring:如果程序只想接收长选项,optstring应该设置为空字符串("")而不是NULL;

longopts:它是指向定义在<getopt.h>中struct option数组第一个元素的指针, struct option结构体如下:

    struct option {
        const char *name;
        int         has_arg;
        int        *flag;
        int         val;
    };

    The meanings of the different fields are:

    name   is the name of the long option.

    has_arg
              is:  no_argument (or 0) if the option does not take an argument;
              required_argument (or 1) if the option requires an argument;  or
              optional_argument  (or  2) if the option takes an optional argu‐
              ment.

    flag      specifies how results are returned for a long option.   If  flag
              is  NULL,  then  getopt_long()  returns  val.  (For example, the
              calling program may set val to the equivalent short option char‐
              acter.)   Otherwise, getopt_long() returns 0, and flag points to
              a variable which is set to val if the option is found, but  left
              unchanged if the option is not found.

    val       is  the value to return, or to load into the variable pointed to
              by flag.

    The last element of the array has to be filled with zeros.

longindex:如果longindex不为NULL,则它指向一个变量,该变量设置为struct option数组中元素的索引;

3.示例:

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

static const char short_options [] = "d:hmru";

static const struct option long_options [] = {
	{ "device",     required_argument,      NULL,           'd' },
	{ "help",       no_argument,            NULL,           'h' },
	{ "mmap",       no_argument,            NULL,           'm' },
	{ "read",       no_argument,            NULL,           'r' },
	{ "userp",      no_argument,            NULL,           'u' },
	{ 0, 0, 0, 0 }
};

static void usage(FILE *fp,int argc,char **argv)
{
	fprintf (fp,
		"Usage: %s [options]\n\n"
		"Options:\n"
		"-d | --device name   Video device name [/dev/video]\n"
		"-h | --help          Print this message\n"
		"-m | --mmap          Use memory mapped buffers\n"
		"-r | --read          Use read() calls\n"
		"-u | --userp         Use application allocated buffers\n"
		"",
		argv[0]);
}

int main(int argc,char **argv)
{
	int index;
	int rec = getopt_long (argc, argv,short_options, long_options,&index);

	switch (rec) {
		case 0: /* getopt_long() flag */
			break;
		case 'd':
			printf("%s\n", optarg);
			break;
		case 'h':
			usage (stdout, argc, argv);
			exit (EXIT_SUCCESS);
		case 'm':
			break;
		case 'r':
			break;
		case 'u':
			break;
		default:
			usage (stderr, argc, argv);
			exit (EXIT_FAILURE);
		}
	return 0;
}

 运行结果:

 在这里使用短选项-d时会报错,但使用短选项-h却正常,因为定义struct option时指定了required_argument,而其他的为no_argument,这个参数决定了传入的长短选项需不需要另外带参数。

4.man手册里的例子:

#include <stdio.h>     /* for printf */
#include <stdlib.h>    /* for exit */
#include <getopt.h>

int
main(int argc, char **argv)
{
    int c;
    int digit_optind = 0;

    while (1) {
        int this_option_optind = optind ? optind : 1;
        int option_index = 0;
        static struct option long_options[] = {
                   {"add",     required_argument, 0,  0 },
                   {"append",  no_argument,       0,  0 },
                   {"delete",  required_argument, 0,  0 },
                   {"verbose", no_argument,       0,  0 },
                   {"create",  required_argument, 0, 'c'},
                   {"file",    required_argument, 0,  0 },
                   {0,         0,                 0,  0 }
        };


        c = getopt_long(argc, argv, "abc:d:012",
                 long_options, &option_index);
        if (c == -1)
            break;

        switch (c) {
        case '0':
        case '1':
        case '2':
             if (digit_optind != 0 && digit_optind != this_option_optind)
                 printf("digits occur in two different argv-elements.\n");
             digit_optind = this_option_optind;
             printf("option %c\n", c);
             break;

        case 'a':
            printf("option a\n");
            break;
        case 'b':
            printf("option b\n");
            break;

        case 'c':
            printf("option c with value '%s'\n", optarg);
            break;
        

       case 'd':
            printf("option d with value '%s'\n", optarg);
            break;

       case '?':
            break;

       default:
            printf("?? getopt returned character code 0%o ??\n", c);
       }
    }

    if (optind < argc) {
        printf("non-option ARGV\-elements: ");
        while (optind < argc)
            printf("%s ", argv[optind++]);
        printf("\n");
    }

    exit(EXIT_SUCCESS);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值