xref: /aosp_15_r20/external/libconfig/examples/c++/example3.cpp (revision 2e9d491483b805f09ea864149eadd5680efcc72a)
1 /* ----------------------------------------------------------------------------
2    libconfig - A library for processing structured configuration files
3    Copyright (C) 2005-2010  Mark A Lindner
4 
5    This file is part of libconfig.
6 
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.
11 
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.
16 
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    ----------------------------------------------------------------------------
21 */
22 
23 #include <iostream>
24 #include <iomanip>
25 #include <cstdlib>
26 #include <libconfig.h++>
27 
28 using namespace std;
29 using namespace libconfig;
30 
31 // This example constructs a new configuration in memory and writes it to
32 // 'newconfig.cfg'.
33 
main(int argc,char ** argv)34 int main(int argc, char **argv)
35 {
36   static const char *output_file = "newconfig.cfg";
37   Config cfg;
38 
39   Setting &root = cfg.getRoot();
40 
41   // Add some settings to the configuration.
42   Setting &address = root.add("address", Setting::TypeGroup);
43 
44   address.add("street", Setting::TypeString) = "1 Woz Way";
45   address.add("city", Setting::TypeString) = "San Jose";
46   address.add("state", Setting::TypeString) = "CA";
47   address.add("zip", Setting::TypeInt) = 95110;
48 
49   Setting &array = root.add("array", Setting::TypeArray);
50 
51   for(int i = 0; i < 10; ++i)
52     array.add(Setting::TypeInt) = 10 * i;
53 
54   // Write out the new configuration.
55   try
56   {
57     cfg.writeFile(output_file);
58     cerr << "New configuration successfully written to: " << output_file
59          << endl;
60 
61   }
62   catch(const FileIOException &fioex)
63   {
64     cerr << "I/O error while writing file: " << output_file << endl;
65     return(EXIT_FAILURE);
66   }
67 
68   return(EXIT_SUCCESS);
69 }
70 
71 // eof
72