#include #include #include #include #include #include "inifile.h" /* char* inifile_cleanstr(char* str) { while (isspace(*str)) str++; int i; for (i = 0; str[i]; i ++) { if } return str; } */ bool inifile_read(const char* filename, inifile_callback callback) { FILE* fp = fopen(filename, "r"); char* inisection = ""; char readbuf[4096] = ""; char* readptr; bool success = true; bool newsection = false; if (!fp) return inifile_cantread; while ((readptr = fgets(readbuf, sizeof(readbuf), fp))) // Loop through each line. { while (isspace(readptr[0])) // Skip whitespace. readptr++; if (readptr[0] == '\0' || readptr[0] == '#' || readptr[0] == '!') // Skip empty lines and comments. continue; else if (readptr[0] == '[' && readptr[1] != ']') // It's a section header. { int i; for (i = 2; readptr[i]; i ++) // Look for the ] if (readptr[i] == ']') break; if (readptr[i]) // Replace with a null or crash with error. readptr[i] = '\0'; else { success = false; break; } if (inisection[0]) free(inisection); inisection = strdup(readptr + 1); // Skip the first [ newsection = true; } else // It's a value. { int i; int equals = 0; for (i = 0; readptr[i]; i ++) // Find the = if (readptr[i] == '=') equals = i; if (readptr[i - 1] == '\n') readptr[i - 1] = '\0'; // Remove the trailing newline. if (equals) { readptr[equals] = '\0'; if (!callback(inisection, newsection, readptr, readptr + equals + 1)) // If the callback is false, exit. break; newsection = false; } else // If there's no equals, crash with error. { success = false; break; } } } if (inisection[0]) free(inisection); fclose(fp); return success; }