|
| 1 | +#include "iniparser.h" |
| 2 | + |
| 3 | +void create_empty_ini_file(void) |
| 4 | +{ |
| 5 | + FILE *ini; |
| 6 | + |
| 7 | + if ((ini = fopen("example.ini", "w")) == NULL) { |
| 8 | + fprintf(stderr, "iniparser: cannot create example.ini\n"); |
| 9 | + return; |
| 10 | + } |
| 11 | + |
| 12 | + fclose(ini); |
| 13 | +} |
| 14 | + |
| 15 | +int write_to_ini(const char *ini_name) |
| 16 | +{ |
| 17 | + void *dictionary; |
| 18 | + FILE *ini_file; |
| 19 | + int ret = 0; |
| 20 | + |
| 21 | + if (!ini_name || !dictionary) { |
| 22 | + fprintf(stderr, "Invalid argurment\n"); |
| 23 | + return -1; |
| 24 | + } |
| 25 | + |
| 26 | + dictionary = iniparser_load(ini_name); |
| 27 | + |
| 28 | + if (!dictionary) { |
| 29 | + fprintf(stderr, "cannot parse file: %s\n", ini_name); |
| 30 | + return -1; |
| 31 | + } |
| 32 | + |
| 33 | + /* set section */ |
| 34 | + ret = iniparser_set(dictionary, "Pizza", NULL); |
| 35 | + |
| 36 | + if (ret < 0) { |
| 37 | + fprintf(stderr, "cannot set section in: %s\n", ini_name); |
| 38 | + ret = -1; |
| 39 | + goto free_dict; |
| 40 | + } |
| 41 | + |
| 42 | + /* set key/value pair */ |
| 43 | + ret = iniparser_set(dictionary, "Pizza:Cheese", "TRUE"); |
| 44 | + |
| 45 | + if (ret < 0) { |
| 46 | + fprintf(stderr, "cannot set key/value in: %s\n", ini_name); |
| 47 | + ret = -1; |
| 48 | + goto free_dict; |
| 49 | + } |
| 50 | + |
| 51 | + ini_file = fopen(ini_name, "w+"); |
| 52 | + |
| 53 | + if (!ini_file) { |
| 54 | + fprintf(stderr, "iniparser: cannot create example.ini\n"); |
| 55 | + ret = -1; |
| 56 | + goto free_dict; |
| 57 | + } |
| 58 | + |
| 59 | + iniparser_dump_ini(dictionary, ini_file); |
| 60 | + fclose(ini_file); |
| 61 | +free_dict: |
| 62 | + iniparser_freedict(dictionary); |
| 63 | + return ret; |
| 64 | +} |
| 65 | + |
| 66 | +int main(int argc, char *argv[]) |
| 67 | +{ |
| 68 | + int ret; |
| 69 | + |
| 70 | + if (argc < 2) { |
| 71 | + create_empty_ini_file(); |
| 72 | + ret = write_to_ini("example.ini"); |
| 73 | + } else |
| 74 | + ret = write_to_ini(argv[1]); |
| 75 | + |
| 76 | + return ret ; |
| 77 | +} |
0 commit comments