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

查看:39
本文介绍了在带有非选项参数的 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.

在选项循环后添加类似于此的代码:

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天全站免登陆