C在GetOpt中使用文件参数 [英] C Using a file argument with GetOpt

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

问题描述

有没有比仅遍历argv []查找不是标志的参数更好的方法来查找文件名??

Is there a better way to find the name of a file than just looping through argv[] looking for an argument that isn't a flag - ?

在这种情况下,可以按任何顺序输入标志(因此optind不会有帮助).

In this case, the flags can be entered in any order (so optind isn't going to help).

即:

/program -p file.txt -s

/program -p file.txt -s

/program -p -s file.txt -b

/program -p -s file.txt -b

/程序file.txt -p -s -a

/program file.txt -p -s -a

int main (int argc, char *argv[]){


char option;
const char *optstring;
optstring = "rs:pih";


while ((option = getopt(argc, argv, optstring)) != EOF) {

    switch (option) {
        case 'r':
            //do something
            break;
        case 's':
          //etc etc 
   }
}

推荐答案

getopt()的手册页中,

默认情况下,getopt()会在扫描时对argv的内容进行置换,以便最终所有非选项都位于末尾.

By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.

因此,给出选项和非选项参数的顺序无关紧要.

So the order in which the options and non-option arguments are given doesn't matter.

使用getopt()处理选项及其参数(如果有).之后,检查optind的值.

Use getopt() to take care of the options and their arguments (if any). After that, check the value of optind.

如手册页所述,

变量optindargv中要处理的下一个元素的索引.

The variable optind is the index of the next element to be processed in argv.

在您的命令中,似乎只有一个非选项参数.如果在正确处理了所有选项之后就是这种情况,则optind必须等于argc-1.

In your command, it seems that there is only one non-option argument. If that's the case after all the options have been correctly processed, optind must be equal to argc-1.

此外,在给出的optstring中,在s之后还有冒号.这意味着如果选项-s存在,则必须有一个参数.

Also, in the optstring you have given, there is colon following s. That means if the option -s is there, it must have an argument.

while ((option = getopt(argc, argv, optstring)) != EOF) {
    switch (option) {
    case 'r':
        //do something
        break;
    case 's':
      //etc etc 
   }
}

//Now get the non-option argument
if(optind != argc-1)
{
    fprintf(stderr, "Invalid number of arguments.");
    return 1;
}
fprintf(stdout, "\nNon-option argument: %s", argv[optind]);

注意:可以以任何顺序提供选项,但是一个选项的参数不能作为另一个选项的参数给出.

Note: The options may be provided in any order but the argument of one option may not be given as the argument of another.

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

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