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 ----------------------------------------------------------------------------
26 #include <libconfig.h++>
29 using namespace libconfig;
31 // This example reads the configuration file 'example.cfg', adds a new
32 // movie record to the movies list, and writes the updated configuration to
35 int main(int argc, char **argv)
37 static const char *output_file = "updated.cfg";
41 // Read the file. If there is an error, report it and exit.
44 cfg.readFile("example.cfg");
46 catch(const FileIOException &fioex)
48 std::cerr << "I/O error while reading file." << std::endl;
51 catch(const ParseException &pex)
53 std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
54 << " - " << pex.getError() << std::endl;
58 // Find the 'movies' setting. Add intermediate settings if they don't yet
60 Setting &root = cfg.getRoot();
62 if(! root.exists("inventory"))
63 root.add("inventory", Setting::TypeGroup);
65 Setting &inventory = root["inventory"];
67 if(! inventory.exists("movies"))
68 inventory.add("movies", Setting::TypeList);
70 Setting &movies = inventory["movies"];
72 // Create the new movie entry.
73 Setting &movie = movies.add(Setting::TypeGroup);
75 movie.add("title", Setting::TypeString) = "Buckaroo Banzai";
76 movie.add("media", Setting::TypeString) = "DVD";
77 movie.add("price", Setting::TypeFloat) = 12.99;
78 movie.add("qty", Setting::TypeInt) = 20;
80 // Write out the updated configuration.
83 cfg.writeFile(output_file);
84 cerr << "Updated configuration successfully written to: " << output_file
88 catch(const FileIOException &fioex)
90 cerr << "I/O error while writing file: " << output_file << endl;