C语言getopt函数使用方法

本文详细介绍了C语言中getopt函数在处理命令行选项和参数时的六个案例,包括选项要求参数、允许无参数选项、选项顺序、额外参数处理以及错误处理等。

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

一、案例1

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

// 这几个是头文件带的变量
// extern char *optarg;
// extern int optind, opterr, optopt;

// -a
// 选项后面一定要有参数,参数和选项之间可以有空格,也可以没空格。解析出的参数放在
// optarg 变量里。 examples:
// ./a.out -a 6
// ./a.out -a6
// ./a.out -a s
// 参数也可以用引号包裹起来,这样可以包含空格.
// ./a.out -a "s b"
// ./a.out -a"s b"
void opt_example1(int argc, char **argv) {
   
  const char *optstr = "a:";
  char ch;
  while ((ch = getopt(argc, argv, optstr)) != -1) {
   
    switch (ch) {
   
    case 'a':
      printf("have option: -a\n");
      printf("the argument of -a is %s\n", optarg);
      break;
    }
  }
}

二、案例2

// 选项后面可以有参数,也可以没有参数。但是有参数情况下,必须没有空格。若有空格,得到的参数是
// null examples:
// ./a.out -b
// ./a.out -b hello
void opt_example2(int argc, char **argv) {
   
  const char *optstr = "b::";
  char ch;
  while ((ch = getopt(argc, argv, optstr)) != -1) {
   
    switch (ch) {
   
    case 'b':
      printf("have option: -b\n");
      printf("the argument of -b is %s\n", optarg);
      break;
    }
  }
}

三、案例3

// -c 选项后面不能有参数。如果有参数,会被当成别的选项. 打印 optarg 得到 null
// examples:
// ./a.out -c
void opt_example3(int argc, char **argv) {
   
  const char *optstr = "c";<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值