0

我正在使用 poptGetArgs 读取单个选项的多个值。但它总是将 null 作为返回值。我在下面发布了我的代码。如果有任何错误,请帮助我解决。

int main(int argc, char **argv)
{
    char filename[ 128 ], symbol[32];
    memset(filename, 0x0, 128);
    memset(symbol, 0x0, 32);

    struct poptOption opttable[] =
    {
        { "file", 'f', POPT_ARG_STRING, filename, INPUT_NAME, "filenames to read", "list of files we need to read" },
        { "symbol", 'r', POPT_ARG_STRING, symbol, SYMBOL, "symbol to view", NULL },
        { NULL, 0, 0, NULL, 0 }
    };
    poptContext options_socket = poptGetContext( NULL, argc, ( const char **)argv, opttable, 0 );

    int optionvalue(0);
    while( optionvalue > -1 )
    {
        optionvalue = poptGetNextOpt( options_socket );
        if(optionvalue == INPUT_NAME)
        {
           const char ** files = poptGetArgs( options_socket );
           if( files == NULL )
           {
              printf("There was an error while reading input files\n");
           }
        }
        else if( optionvalue == SYMBOL)
        {
           strcpy(symbol, poptGetOptArg( options_socket ));
           printf("symbol you are giving as input is :%s, option value:%d\n", symbol, optionvalue);
        }
    }
    return 0;
}
4

1 回答 1

0

这是因为我试图在中间读取剩余的参数(在文件选项读取之后)。但是所有剩余的选项应该只在最后阅读。意味着我需要在 while( optionvalue > -1 ) 循环之后读取参数。我修改后的代码是

enum
{
   INPUT_NAME=1,
   SYMBOL
};
int main(int argc, char **argv)
{
    char filename[ 128 ], symbol[32];
    memset(filename, 0x0, 128);
    memset(symbol, 0x0, 32);

    struct poptOption opttable[] =
    {
        { "file", 'f', POPT_ARG_STRING, filename, INPUT_NAME, "filenames to read", "list of files we need to read" },
        { "symbol", 'r', POPT_ARG_STRING, symbol, SYMBOL, "symbol to view", NULL },
        { NULL, 0, 0, NULL, 0 }
    };
    poptContext options_socket = poptGetContext( NULL, argc, ( const char **)argv, opttable, 0 );

    int optionvalue(0);
    while( optionvalue > -1 )
    {
        optionvalue = poptGetNextOpt( options_socket );
        if(optionvalue == INPUT_NAME)
        {
           strcpy(filename, poptGetOptArg( options_socket));
           printf("file name you are giving as input is :%s, option value:%d\n", filename, optionvalue);
//           const char ** files = poptGetArgs( options_socket );
        }
        else if( optionvalue == SYMBOL)
        {
           strcpy(symbol, poptGetOptArg( options_socket ));
           printf("symbol you are giving as input is :%s, option value:%d\n", symbol, optionvalue);
        }
    }
    const char ** files = poptGetArgs( options_socket );
    if(files == NULL)
    {
        printf("There are no other files left\n");
    }
    return 0;
}

现在工作正常。

于 2013-04-30T05:16:12.713 回答