Per Ben Hiett, add support for heap (malloc) allocation for INI files with very long lines.
diff --git a/ini.c b/ini.c
index 15546e9..24295f5 100644
--- a/ini.c
+++ b/ini.c
@@ -13,7 +13,10 @@
#include "ini.h"
-#define MAX_LINE 200
+#if !INI_USE_STACK
+#include <stdlib.h>
+#endif
+
#define MAX_SECTION 50
#define MAX_NAME 50
@@ -62,7 +65,11 @@
void* user)
{
/* Uses a fair bit of stack (use heap instead if you need to) */
- char line[MAX_LINE];
+#if INI_USE_STACK
+ char line[INI_MAX_LINE];
+#else
+ char* line;
+#endif
char section[MAX_SECTION] = "";
char prev_name[MAX_NAME] = "";
@@ -73,8 +80,15 @@
int lineno = 0;
int error = 0;
+#if !INI_USE_STACK
+ line = (char*)malloc(INI_MAX_LINE);
+ if (!line) {
+ return -2;
+ }
+#endif
+
/* Scan through file line by line */
- while (fgets(line, sizeof(line), file) != NULL) {
+ while (fgets(line, INI_MAX_LINE, file) != NULL) {
lineno++;
start = line;
@@ -138,6 +152,10 @@
}
}
+#if !INI_USE_STACK
+ free(line);
+#endif
+
return error;
}
diff --git a/ini.h b/ini.h
index f337a6a..4ad8c64 100644
--- a/ini.h
+++ b/ini.h
@@ -27,7 +27,8 @@
of handler call). Handler should return nonzero on success, zero on error.
Returns 0 on success, line number of first error on parse error (doesn't
- stop on first error), or -1 on file open error.
+ stop on first error), -1 on file open error, or -2 on memory allocation
+ error (only when INI_USE_STACK is zero).
*/
int ini_parse(const char* filename,
int (*handler)(void* user, const char* section,
@@ -54,6 +55,16 @@
#define INI_ALLOW_BOM 1
#endif
+/* Nonzero to use stack, zero to use heap (malloc/free). */
+#ifndef INI_USE_STACK
+#define INI_USE_STACK 1
+#endif
+
+/* Maximum line length for any line in INI file. */
+#ifndef INI_MAX_LINE
+#define INI_MAX_LINE 200
+#endif
+
#ifdef __cplusplus
}
#endif