Created
April 28, 2011 19:11
-
-
Save OrangeTide/947070 to your computer and use it in GitHub Desktop.
.ini file parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This software is public domain. No copyright is claimed. | |
* Jon Mayo April 2011 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
/* Load an .ini format file | |
* filename - path to a file | |
* report - callback can return non-zero to stop, the callback error code is | |
* returned from this function. | |
* return - return 0 on success | |
*/ | |
int ini_load(const char *filename, | |
int (*report)(const char *section, const char *name, const char *value)) | |
{ | |
char name[64]; | |
char value[256]; | |
char section[128] = ""; | |
char *s; | |
FILE *f; | |
int cnt; | |
f = fopen(filename, "r"); | |
if (!f) { | |
perror(filename); | |
return -1; | |
} | |
while (!feof(f)) { | |
if (fscanf(f, "[%127[^];\n]]\n", section) == 1) { | |
} else if ((cnt = fscanf(f, " %63[^=;\n] = %255[^;\n]", | |
name, value))) { | |
if (cnt == 1) | |
*value = 0; | |
for (s = name + strlen(name) - 1; s > name && | |
isspace(*s); s--) | |
*s = 0; | |
for (s = value + strlen(value) - 1; s > value && | |
isspace(*s); s--) | |
*s = 0; | |
report(section, name, value); | |
} | |
fscanf(f, " ;%*[^\n]"); | |
fscanf(f, " \n"); | |
} | |
fclose(f); | |
return 0; | |
} | |
static int my_callback(const char *section, const char *name, const char *value) | |
{ | |
fprintf(stdout, "[%s] '%s'='%s'\n", section, name, value); | |
return 0; | |
} | |
int main(int argc, char **argv) | |
{ | |
int i, e; | |
for(i = 1; i < argc; i++) { | |
e = ini_load(argv[i], my_callback); | |
if (e) | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment