在命令行选项解析器中切换选项名称

时间:2013-06-28 23:27:13

标签: c command-line

我尝试编写代码,其中switch'--feature'可以有一个相反的效果,称为'--no-feature'。

伪代码:

static gboolean
option_feature_cb (const gchar *option_name, const gchar *value, gpointer data, GError **error)
{
    if (strcmp(option_name, "no-feature") != 0)
        goto error;
    else
        x = 0;
    if (strcmp(option_name, "feature") != 0)
        goto error;
    else
        x = 1;

    return TRUE;
error:
    g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
            _("invalid option name (%s), must be '--feature' or '--no-feature'"), value);
    return FALSE;

}

int main(int argc, char* argv[])
{

.................................................................................................................
const GOptionEntry entries[] = {
    { "[no-]feature", '\0', 0, G_OPTION_ARG_CALLBACK, option_feature_cb, N_("Disable/enable feature"), NULL },
    { NULL }
};

我需要帮助才能编写代码来执行此操作。

更新

我在Ruby中找到了这个解析命令,但我在c和gnome中使用了什么:

开关可以有一个否定的形式。交换机 - 可以有一个相反的效果,称为--no-negated。要在开关描述字符串中对此进行描述,请将替代部分放在括号中: - [no-]否定。如果遇到第一个表单,则true将传递给块,如果遇到第二个表单,则将阻止false。

options[:neg] = false
opts.on( '-n', '--[no-]negated', "Negated forms" ) do|n|
    options[:neg] = n
end

1 个答案:

答案 0 :(得分:1)

您对no-feature的测试会阻止检查feature,因为它会在失败时直接转到error。以下应该会更好:

static gboolean
option_feature_cb (const gchar *option_name, const gchar *value, gpointer data, GError **error)
{
    if (strcmp(option_name, "no-feature") == 0) {
        x = 0;
        return TRUE;
    } elseif (strcmp(option_name, "feature") == 0) {
        x = 1;
        return TRUE;
    } else {
        g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
            _("invalid option name (%s), must be '--feature' or '--no-feature'"), value);
        return FALSE;
    }
}