1 /* ----------------------------------------------------------------------------
2 libconfig - A library for processing structured configuration files
3 Copyright (C) 2005-2010 Mark A Lindner
5 This file is part of libconfig.
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public License
9 as published by the Free Software Foundation; either version 2.1 of
10 the License, or (at your option) any later version.
12 This library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
17 You should have received a copy of the GNU Library General Public
18 License along with this library; if not, see
19 <http://www.gnu.org/licenses/>.
20 ----------------------------------------------------------------------------
25 #include <libconfig.h>
27 /* This example reads the configuration file 'example.cfg', adds a new
28 * movie record to the movies list, and writes the updated configuration to
32 int main(int argc, char **argv)
34 static const char *output_file = "updated.cfg";
36 config_setting_t *root, *setting, *movie;
40 /* Read the file. If there is an error, report it and exit. */
41 if(! config_read_file(&cfg, "example.cfg"))
43 fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
44 config_error_line(&cfg), config_error_text(&cfg));
49 /* Find the 'movies' setting. Add intermediate settings if they don't yet
52 root = config_root_setting(&cfg);
54 setting = config_setting_get_member(root, "inventory");
56 setting = config_setting_add(root, "inventory", CONFIG_TYPE_GROUP);
58 setting = config_setting_get_member(setting, "movies");
60 setting = config_setting_add(setting, "movies", CONFIG_TYPE_LIST);
62 /* Create the new movie entry. */
63 movie = config_setting_add(setting, NULL, CONFIG_TYPE_GROUP);
65 setting = config_setting_add(movie, "title", CONFIG_TYPE_STRING);
66 config_setting_set_string(setting, "Buckaroo Banzai");
68 setting = config_setting_add(movie, "media", CONFIG_TYPE_STRING);
69 config_setting_set_string(setting, "DVD");
71 setting = config_setting_add(movie, "price", CONFIG_TYPE_FLOAT);
72 config_setting_set_float(setting, 12.99);
74 setting = config_setting_add(movie, "qty", CONFIG_TYPE_INT);
75 config_setting_set_float(setting, 20);
77 config_set_options(&cfg, 0);
79 /* Write out the updated configuration. */
80 if(! config_write_file(&cfg, output_file))
82 fprintf(stderr, "Error while writing file.\n");
87 fprintf(stderr, "Updated configuration successfully written to: %s\n",