Skip to content

Commit

Permalink
Add example showing how to write INI files
Browse files Browse the repository at this point in the history
refs #143
  • Loading branch information
lmoellendorf committed Mar 2, 2024
1 parent 9dfa7fe commit 80c9d6f
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 1 deletion.
5 changes: 4 additions & 1 deletion example/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ RM ?= rm -f

default: all

all: iniexample parse
all: iniexample iniwrite parse

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

iniwrite: iniwrite.c
$(CC) $(CFLAGS) -o iniwrite iniwrite.c -I../src -L.. -liniparser

parse: parse.c
$(CC) $(CFLAGS) -o parse parse.c -I../src -L.. -liniparser

Expand Down
77 changes: 77 additions & 0 deletions example/iniwrite.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include "iniparser.h"

void create_empty_ini_file(void)
{
FILE *ini;

if ((ini = fopen("example.ini", "w")) == NULL) {
fprintf(stderr, "iniparser: cannot create example.ini\n");
return;
}

fclose(ini);
}

int write_to_ini(const char *ini_name)
{
void *dictionary;
FILE *ini_file;
int ret = 0;

if (!ini_name || !dictionary) {
fprintf(stderr, "Invalid argurment\n");
return -1;
}

dictionary = iniparser_load(ini_name);

if (!dictionary) {
fprintf(stderr, "cannot parse file: %s\n", ini_name);
return -1;
}

/* set section */
ret = iniparser_set(dictionary, "Pizza", NULL);

if (ret < 0) {
fprintf(stderr, "cannot set section in: %s\n", ini_name);
ret = -1;
goto free_dict;
}

/* set key/value pair */
ret = iniparser_set(dictionary, "Pizza:Cheese", "TRUE");

if (ret < 0) {
fprintf(stderr, "cannot set key/value in: %s\n", ini_name);
ret = -1;
goto free_dict;
}

ini_file = fopen(ini_name, "w+");

if (!ini_file) {
fprintf(stderr, "iniparser: cannot create example.ini\n");
ret = -1;
goto free_dict;
}

iniparser_dump_ini(dictionary, ini_file);
fclose(ini_file);
free_dict:
iniparser_freedict(dictionary);
return ret;
}

int main(int argc, char *argv[])
{
int ret;

if (argc < 2) {
create_empty_ini_file();
ret = write_to_ini("example.ini");
} else
ret = write_to_ini(argv[1]);

return ret ;
}

0 comments on commit 80c9d6f

Please sign in to comment.