poptGetArgs返回null。

时间:2013-04-29 11:29:32

标签: c linux getopt getopts

我正在使用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;
}

1 个答案:

答案 0 :(得分: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;
}

现在工作正常。