summaryrefslogtreecommitdiffstats
path: root/src/jv_file.c
diff options
context:
space:
mode:
authorDavid Tolnay <dtolnay@gmail.com>2015-08-23 20:36:11 -0700
committerDavid Tolnay <dtolnay@gmail.com>2015-08-23 20:36:11 -0700
commit0c93eb3379241dc4775718a9d39f54a6c4de20d6 (patch)
tree67bb5510adb707d54c6f72b51b0718578a2caf5c /src/jv_file.c
parent891f28ef5e406a8d2156ad88d0244ab03fe490eb (diff)
Move source files to src/
Diffstat (limited to 'src/jv_file.c')
-rw-r--r--src/jv_file.c49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/jv_file.c b/src/jv_file.c
new file mode 100644
index 00000000..33d327c7
--- /dev/null
+++ b/src/jv_file.c
@@ -0,0 +1,49 @@
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "jv.h"
+
+jv jv_load_file(const char* filename, int raw) {
+ FILE* file = fopen(filename, "r");
+ struct jv_parser* parser;
+ jv data;
+ if (!file) {
+ return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",
+ filename,
+ strerror(errno)));
+ }
+ if (raw) {
+ data = jv_string("");
+ } else {
+ data = jv_array();
+ parser = jv_parser_new(0);
+ }
+ while (!feof(file) && !ferror(file)) {
+ char buf[4096];
+ size_t n = fread(buf, 1, sizeof(buf), file);
+ if (raw) {
+ data = jv_string_concat(data, jv_string_sized(buf, (int)n));
+ } else {
+ jv_parser_set_buf(parser, buf, n, !feof(file));
+ jv value;
+ while (jv_is_valid((value = jv_parser_next(parser))))
+ data = jv_array_append(data, value);
+ if (jv_invalid_has_msg(jv_copy(value))) {
+ jv_free(data);
+ data = value;
+ break;
+ }
+ }
+ }
+ if (!raw)
+ jv_parser_free(parser);
+ int badread = ferror(file);
+ if (fclose(file) != 0 || badread) {
+ jv_free(data);
+ return jv_invalid_with_msg(jv_string_fmt("Error reading from %s",
+ filename));
+ }
+ return data;
+}