UCI C API - 如何使用列表选项

时间:2016-06-24 20:27:58

标签: c openwrt

使用UCI,我们可以使用以下命令检索整个列表:

$ uci get system.ntp.server

这将阅读下面的配置类型:

config system
    option hostname 'OpenWrt'
    option timezone 'UTC'

config timeserver 'ntp'
    list server '0.openwrt.pool.ntp.org'
    list server '1.openwrt.pool.ntp.org'
    list server '2.openwrt.pool.ntp.org'
    list server '3.openwrt.pool.ntp.org'
    option enabled '1'
    option enable_server '0'

返回一个长字符串中的所有ntp服务器。

0.openwrt.pool.ntp.org 1.openwrt.pool.ntp.org 2.openwrt.pool.ntp.org 3.openwrt.pool.ntp.org

我希望使用C api实现相同(或等效)。

我把以下代码放在一起:

#include <uci.h>
#include <string.h>
void main()
{
    //char path[] = "system.ntp.enabled";
    char path[] = "system.ntp.server";
    char buffer[80];
    get_config_entry(path, &buffer);
    printf("%s\n", buffer);

}

int get_config_entry (char *path, char *buffer)
{
  struct uci_context *c;
  struct uci_ptr ptr;

  c = uci_alloc_context ();
  if (uci_lookup_ptr (c, &ptr, path, true) != UCI_OK)
    {
      uci_perror (c, "XXX");
      return 1;
    }

  strcpy(buffer, ptr.o->v.string);
  uci_free_context (c);
  return 0;
}

运行它只会在输出字符串中返回垃圾。

我应该如何使用UCI C API处理列表内容?

1 个答案:

答案 0 :(得分:1)

如果请求列表元素,则它存储在v.list而不是v.string。

我在uci cli代码中找到了uci_show_value函数,它有很多帮助。我设法获得以下代码以便与列表选项配合使用。

#include <uci.h>
#include <string.h>

static const char *delimiter = " ";

static void uci_show_value(struct uci_option *o)
{
    struct uci_element *e;
    bool sep = false;

    switch(o->type) {
    case UCI_TYPE_STRING:
        printf("%s\n", o->v.string);
        break;
    case UCI_TYPE_LIST:
        uci_foreach_element(&o->v.list, e) {
            printf("%s%s", (sep ? delimiter : ""), e->name);
            sep = true;
        }
        printf("\n");
        break;
    default:
        printf("<unknown>\n");
        break;
    }
}

int show_config_entry (char *path)
{
  struct uci_context *c;
  struct uci_ptr ptr;

  c = uci_alloc_context ();
  if (uci_lookup_ptr (c, &ptr, path, true) != UCI_OK)
    {
      uci_perror (c, "get_config_entry Error");
      return 1;
    }

  uci_show_value(ptr.o);
  uci_free_context (c);
  return 0;
}

void main()
{
    char path[] = "system.ntp.server";
    show_config_entry(path);

}
相关问题