解析非标准参数 [英] Parsing non-standard arguments
本文介绍了解析非标准参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个程序,将源文件中的一个或多个字符替换为一个或多个指定的字符,并将新文本写入目标文件。
例如,以下对程序";Sub";的调用都会导致将src.txt中的‘a’和‘b’实例分别替换为‘x’和‘y’,并将其写入est.txt。
$ sub --ab -+xy -i src.txt -o dest.txt
$ sub -i src.txt -o dest.txt --ab -+xy
$ sub -o dest.txt --ab -i src.txt -+xy
$ sub --ab -o dest.txt -+xy -i src.txt
我已经研究了C的getopt(),但我认为它没有涵盖选项后面可能的多个字符。
程序接受参数的方式是固定的。在某些情况下,文本文件中可能有多个字母需要替换,我该如何解析这些参数?并处理任何参数排序?
我不能打开字符串,但我不能用选项中的特殊字符创建枚举。据我所知,getopt()并不能处理我的程序所期望的参数。所以我只剩下以下非常不完整的代码:int main(int argc, char * argv[]) {
// help message displayed for "sub" and "sub -h"
if (argc == 1 || strcmp(argv[1], "-h") == 0){
helpMsg();
} else {
// process rest of argv
int i = 2;
while (argc != 0) {
char *opt = argv[i];
switch(opt){
}
i++;
argc--;
}
}
return 0;
}
推荐答案
尽管它非常不规范,但此代码可以在Mac上运行:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int opt;
while ((opt = getopt(argc, argv, "i:o:+:-:")) != -1)
{
switch (opt)
{
case '+':
case '-':
case 'i':
case 'o':
printf("Got '-%c' argument '%s'
", opt, optarg);
break;
default:
printf("!! FAIL !! optopt = %c
", optopt);
break;
}
}
return 0;
}
它告诉getopt()
-
是需要参数的选项‘Letter’(字符),而+
是需要参数的选项字符。我可以这样运行它(getopt23.c
中的代码编译为getopt23
):
$ ./getopt23 -i input -o output --ab -+xy
Got '-i' argument 'input'
Got '-o' argument 'output'
Got '--' argument 'ab'
Got '-+' argument 'xy'
$
请注意,此代码中-i
和输入文件ETC之间的强制空格不是强制的:
$ ./getopt23 -iinput -ooutput -+ xy --ab
Got '-i' argument 'input'
Got '-o' argument 'output'
Got '-+' argument 'xy'
Got '--' argument 'ab'
$ ./getopt23 -iinput -ooutput -+ xy -- ab
Got '-i' argument 'input'
Got '-o' argument 'output'
Got '-+' argument 'xy'
$
这两个参数中的第二个很有趣----
表示选项的结束,ab
是一个非选项参数(通常是文件名)。如果使用循环扩展代码:
for (int i = optind; i < argc; i++)
printf("Plain argument %d: '%s'
", i, argv[i]);
则ab
(而不是--
)将被打印为"纯参数"。(POSIXUtility Syntax Guidelines将名称‘操作数’用于我所称的‘非选项参数’。)
--
或-+
选项的替换字符串’。使用常规getopt()
,要做到这一点而不引起未定义的行为是极其困难的。
我以前commented那个:
您说得对,无论是(POSIX)
getopt()
还是任何标准变体都不会处理这个符号--这就是本文中"非标准"的意思。
我必须部分撤回这一声明。如果您必须将-i
和输入文件名放在单独的参数中,而不是以-iinput
的形式呈现,并且-o
和输出文件名类似,并且如果字符集必须附加到--
和-+
,则不能可靠地使用getopt()
。如果该表示法可以灵活使用,您毕竟可以使用getopt()
,而我之前评论是过度陈述。
这篇关于解析非标准参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文