在C使用getopt的非选项参数 [英] Using getopt in C with non-option arguments

查看:553
本文介绍了在C使用getopt的非选项参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C一个小程序,有很多命令行参数的交易,所以我决定用getopt的对它们进行排序适合我。

I'm making a small program in C that deals with a lot of command line arguments, so I decided to use getopt to sort them for me.

不过,我想两个非选项参数(源文件和目标文件)是强制性的,所以你必须让他们作为参数调用时程序,即使没有标志或其他参数。

However, I want two non-option arguments (source and destination files) to be mandatory, so you have to have them as arguments while calling the program, even if there's no flags or other arguments.

下面是什么,我有标志来处理参数的简化版本:

Here's a simplified version of what I have to handle the arguments with flags:

while ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
    switch (c) {
        case 'i': {
            i = (int)atol(optarg);
        }
        case 'd': {
            d = (int)atol(optarg);
        }
        case 'b':
            buf = 1;
            break;
        case 't':
            time = 1;
            break;
        case 'w':
            w = (int)atol(optarg);
            break;
        case 'h':
            h = (int)atol(optarg);
            break;
        case 's':
            s = (int)atol(optarg);
            break;
        default:
            break;
    }
}

如何修改这使非选项参数也是处理?

How do I edit this so that non-option arguments are also handled?

我也希望能够有非选项要么之前的的选项后,怎么会是这样处理的?

I also want to be able to have the non-options either before or after the options, so how would that be handled?

推荐答案

getopt的设置 OPTIND 变量来表示下一个参数的位置。

getopt sets the optind variable to indicate the position of the next argument.

添加与此类似code 选项循环:

Add code similar to this after the options loop:

if (argv[optind] == NULL || argv[optind + 1] == NULL) {
  printf("Mandatory argument(s) missing\n");
  exit(1);
}

编辑:

如果你想允许普通参数的选项后,你可以做一些类似的:

If you want to allow options after regular arguments you can do something similar to this:

while (optind < argc) {
  if ((c = getopt(argc, argv, "i:d:btw:h:s:")) != -1) {
    // Option argument
    switch (c) {
        case 'i': {
            i = (int)atol(optarg);
        }
        case 'd': {
            d = (int)atol(optarg);
        }
        case 'b':
            buf = 1;
            break;
        case 't':
            time = 1;
            break;
        case 'w':
            w = (int)atol(optarg);
            break;
        case 'h':
            h = (int)atol(optarg);
            break;
        case 's':
            s = (int)atol(optarg);
            break;
        default:
            break;
    }
    else {
        // Regular argument
        <code to handle the argument>
        optind++;  // Skip to the next argument
    }
}

这篇关于在C使用getopt的非选项参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆