Skip to content

Commit 80c9d6f

Browse files
committed
Add example showing how to write INI files
refs #143
1 parent 9dfa7fe commit 80c9d6f

File tree

2 files changed

+81
-1
lines changed

2 files changed

+81
-1
lines changed

example/Makefile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@ RM ?= rm -f
1212

1313
default: all
1414

15-
all: iniexample parse
15+
all: iniexample iniwrite parse
1616

1717
iniexample: iniexample.c
1818
$(CC) $(CFLAGS) -o iniexample iniexample.c -I../src -L.. -liniparser
1919

20+
iniwrite: iniwrite.c
21+
$(CC) $(CFLAGS) -o iniwrite iniwrite.c -I../src -L.. -liniparser
22+
2023
parse: parse.c
2124
$(CC) $(CFLAGS) -o parse parse.c -I../src -L.. -liniparser
2225

example/iniwrite.c

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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

Comments
 (0)