gpt4 book ai didi

c - 通过 getopt 传递一些参数

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:38 25 4
gpt4 key购买 nike

我想做的是从命令行获取更多参数,并让它们在新的一行上输出每个参数。我怎么能通过保持相同的结构来做到这一点?我还想获得 -f 输出。

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>

int
main(int argc, char *argv[])
{
int nod1, opt;
int nsecs, nod2;

nsecs = 0;
nod2 = 0;
nod1 = 0;

while ((opt = getopt(argc, argv, "nf:")) != -1) {
switch (opt) {
case 'n':
nod1 = 1;
break;
case 'f':
nsecs = atoi(optarg);
nod2 = 1;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
argv[0]);
exit(EXIT_FAILURE);
}
}

printf("nod1=%d; nod2=%d; optind=%d\n", nod1, nod2, optind);

if (optind >= argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}

printf("Output = %s\n", argv[optind]);

/* Other code omitted */

exit(EXIT_SUCCESS);
}

来自评论:

The arguments after the -f should be optional and I want to list every single one that has been passed under one another...

$ ./partitioner -n 4 -f Test1 Test2 Test3 Test4
Number:4
File names:
Output = Test1
Output = Test2
Output = Test3
Output = Test4
$

最佳答案

考虑到 Jonathan Leffler 的评论,我编辑了我的答案:

POSIX getopt() doesn't really handle optional arguments sensibly. GNU getopt() is a bit better, but not by much. Avoid them whenever you can.

我提出了一个简单的想法,但可以解决您的问题,所以这里是:

argv 中,您有一个按它们在推荐行中排序的参数列表,对吗?因此,如果您可以在 argv 中找到任何 -f,这意味着 -f 之后的所有参数,直到另一个选项或参数列表的末尾您要打印的选项。

-f 到另一个选项(在本例中为 -g):

./command -a A -b B -f one two tree -g G

-f到结束

./command -a A -b B -f one two tree

这里有一个辅助函数可以做到这一点:

bool get_f_args(int argc, char *argv[], int &count, int* indexes)
{
bool f_found = false, parsing_f_args = false;
int collect_count = 0;

if (argc < 3) return false; // "./command -f" are just two values for argv
// we need at least 3.

// Check for every argument in the argument list.
for (int i = 1; i < argc; i++)
{

// If you found another option
// stop collecting args.
if (argv[i][0] == '-' && parsing_f_args) // options starts with '-' character.
parsing_f_args = false;

if (parsing_f_args)
indexes[count++] = i;

// If some is "-f" then the following are the
// ones you're looking for. We check for -f after
//
// indexes[count++] = i;
//
// in roder to avoid adding -f index to indexes.
if (strcmp("-f", argv[i]) == 0) {
parsing_f_args = true;
f_found = true;
}

}
return f_found;
}

这是一个使用示例:

int main(int argc, char* argv[])
{
int count = 0;
int indexes[10];

bool f_found = get_f_args(argc, argv, count, indexes);
if (f_found){
for (int i = 0; i < count; i++)
printf("Ouput = %s\n", argv[indexes[i]]);
}

return 0;
}

关于c - 通过 getopt 传递一些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24575391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com