[英]I'd like a C program to accept arguments from linux command line
我正在尝试将文本作为输入进行分析,该文本将根据输入到命令提示符中的参数及其值(例如./a.out -a -b 20 -c 3
)以任何顺序进行修改和打印,并且它们是可选的,根本不必输入。 我如何将这些参数实现到 C 代码中,以及如何找出它们的值? (为了便于解释,您可以使用前面提到的 -a、-b 和 -c。)
谢谢你。
(我不是在寻找对此的投票。感谢@SteveFriedl。)
由于我从未听说过getopt()
并且一直为这种事情编写自己的解析器而感到内疚,请参见下面的示例。
请注意, getopt
似乎只接受单字符参数名称。 例如,您可以使用-f hello.text
,但不能使用-f hello.text
-filename hello.txt
。 optind
和optarg
是(呃)在unistd.h
声明的全局变量。
(请注意,通过逐步执行argv[]
自己实现这一点并不困难,这可能会产生更灵活的解决方案。)
// copied from https://www.geeksforgeeks.org/getopt-function-in-c-to-parse-command-line-arguments/
// Program to illustrate the getopt()
// function in C
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int opt;
// put ':' in the starting of the
// string so that program can
//distinguish between '?' and ':'
while((opt = getopt(argc, argv, “:if:lrx”)) != -1)
{
switch(opt)
{
case ‘i’:
case ‘l’:
case ‘r’:
printf(“option: %c\n”, opt);
break;
case ‘f’:
printf(“filename: %s\n”, optarg);
break;
case ‘:’:
printf(“option needs a value\n”);
break;
case ‘?’:
printf(“unknown option: %c\n”, optopt);
break;
}
}
// optind is for the extra arguments
// which are not parsed
for(; optind < argc; optind++){
printf(“extra arguments: %s\n”, argv[optind]);
}
return 0;
}
然后,
./a.out -i -f file.txt -lr -x 'hero'
产生
option: i
filename: file.txt
option: l
option: r
unknown option: x
extra arguments: hero
通常你像这样声明你的主函数,
int main( int argc, char *argv[] ) {}
然后,当你从命令行调用你的程序时,
./a.out 1 2 3
argc
将是一个包含 4(传递的参数数量)的 int
在argv[1]
到argv[3]
你分别有指向参数 1 到 3 的指针。 而在argv[0]
您有一个指向程序名称的指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.