aboutsummaryrefslogtreecommitdiffstats
path: root/samples/c/sample3.c
blob: 22f5f36aa7ab714cb08212f20d44a68a3fc0535c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*************************************************************************
 ** Sample3
 ** Load sample.cfg and try to add a setting "foo"..
 **   on success save to testfoo.cfg
 *************************************************************************/

#include <stdio.h>
#include <libconfig.h>

/***************************************************************************/

/*
 */

int print_path(config_setting_t *setting)
{
  if(setting)
  {
    const char *name = config_setting_name(setting);
    
    if(print_path(config_setting_parent(setting)))
      putchar('.');

    if(! config_setting_is_root(setting))
    {
      if(! name)
        printf("[%d]", config_setting_index(setting));
      else
        printf(name);

      return(1);
    }
  }

  return(0);
}

/*
 */

int main()
{
  struct config_t cfg;
  config_setting_t *setting = NULL;
  int i;
  
  do
  {
    /* Initialize the configuration */
    config_init(&cfg);
    
    /* Load the file */
    printf("loading [sample.cfg]...");
    if (!config_read_file(&cfg, "sample.cfg"))
    {
      puts("failed");
      break;
    }
    
    puts("ok");

    /* Add setting "foo" */
    printf("add setting \"foo\"...");
    setting = config_setting_add(cfg.root, "foo", CONFIG_TYPE_INT);
    if (!setting)
    {
      puts("failed");
      break;
    }
    
    config_setting_set_int(setting, 1234);
    puts("ok");

    /** Look up an array element */
    printf("looking up array element...");
    setting = config_lookup(&cfg, "arrays.values.[0]");
    if(! setting)
    {
      puts("failed");
      break;
    }

    printf("value is: %d\n", config_setting_get_int(setting));
    printf("path is: ");
    print_path(setting);
    putchar('\n');
    
    /* Save to "samplefoo.cfg" */
    printf("saving [samplefoo.cfg]...");
    config_write_file(&cfg, "samplefoo.cfg");
    puts("ok");
    
    puts("Done!");
  }
  while(0);

  /* Free the configuration */
  config_destroy(&cfg);

  return 0;
}


/***************************************************************************/