C 使用带有 GetOpt 的文件参数

C Using a file argument with GetOpt

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

在这种情况下,可以按任何顺序输入标志(因此 optind 无济于事)。

即:

/程序-pfile.txt-s

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

/程序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()

的手册页

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

所以给出选项和非选项参数的顺序并不重要。

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

的值

如手册页所述,

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

在你的命令中,似乎只有一个非选项参数。如果在正确处理所有选项后出现这种情况,optind 必须等于 argc-1.

此外,在您提供的 optstring 中,s 后面有一个冒号。这意味着如果选项 -s 存在,它必须有一个参数。

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]);

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