c - 使用 getopt 在 C 中解析参数

标签 c parsing getopt

我正在尝试解析传递给我的程序的参数,以便在函数中使用它们。 参数的格式是:

emp ­­-p one.txt two.txt three.bin ­-­o file.emp

我想在 char **arg_pack 中保存 -p 之后的参数,在 char **arg_output 中保存 -o 之后的参数.

这是我的部分代码:

#define OPTION_STRING "p:u:r:l:d:o:i:ah"
#define OP_ARG_PACK        'p'

extern char *optarg;
extern int optind, opterr, optopt;

char **arg_pack;
char **arg_output;

int arg_pack_count = 0;
int arg_output_count = 0;

while ((res = getopt(argc, argv, OPTION_STRING)) != -1 )
{
    if (res == (int) OP_ARG_PACK)
    {   
        int index = optind - 1;
        arg_pack_count++;
        while(index < argc)
        {   
            *arg_pack = malloc(strlen(argv[index])+1 );
            strcpy(arg_pack[index], argv[index]);
            index++;

            if ( (index<argc) && ((argv[index])[0] == '-') )
            {         
                optind = index - 1;
                break;
            }
        }
        emp_pack(arg_pack,arg_output);
    }
}

它给我一个段错误。这是为什么?

最佳答案

根据 Linux 手册页

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

因此,当您尝试在 while 循环内索引 argv 时,您索引的 argv 可能与您开始使用的 argv 不同。

关于c - 使用 getopt 在 C 中解析参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164338/

相关文章:

c - 获取函数的返回值

android json多维数组

javascript - JavaScript 如何检测正则表达式?

c++ - 如何正确调用getopt函数

c - 为什么 gdb 得到错误的 "optind"变量值?

cmocka,如何检查函数指针

c - 在 C 中从表中分配指针时遇到问题

c - 链表崩溃,c

node.js - 从 JSON 文件读取并解析原始数据

bash - 如何将长选项传递给 bash 脚本?