jv_file.c
This file
Path
src/jv_file.c
95 lines · 2.6 KiB · C
Last changed by
Strip UTF-8 BOM at the start of each input file (#3657)itchynybefore adoptione001deb
History of this fileTake it
1#include <sys/stat.h>23#include <errno.h>4#include <fcntl.h>5#include <stdio.h>6#include <stdlib.h>7#include <string.h>8#include <unistd.h>9#include "jv.h"10#include "jv_unicode.h"1112jv jv_load_file(const char* filename, int raw) {13 struct stat sb;14 int fd = open(filename, O_RDONLY);15 if (fd == -1) {16 return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",17 filename,18 strerror(errno)));19 }20 if (fstat(fd, &sb) == -1 || S_ISDIR(sb.st_mode)) {21 close(fd);22 return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",23 filename,24 "It's a directory"));25 }26 FILE* file = fdopen(fd, "r");27 struct jv_parser* parser = NULL;28 jv data;29 if (!file) {30 close(fd);31 return jv_invalid_with_msg(jv_string_fmt("Could not open %s: %s",32 filename,33 strerror(errno)));34 }35 if (raw) {36 data = jv_string("");37 } else {38 data = jv_array();39 parser = jv_parser_new(0);40 }4142 // To avoid mangling UTF-8 multi-byte sequences that cross the end of our read43 // buffer, we need to be able to read the remainder of a sequence and add that44 // before appending.45 char buf[4096 + 4];46 int at_file_start = 1;47 while (!feof(file) && !ferror(file)) {48 size_t n = fread(buf, 1, sizeof(buf) - 4, file);49 if (n == 0)50 continue;5152 char *end = buf + n;53 int len = 0;54 if (jvp_utf8_backtrack(end - 1, buf, &len) && len > 0 &&55 !feof(file) && !ferror(file)) {56 n += fread(end, 1, len, file);57 }5859 char *p = buf;60 if (at_file_start) {61 // Strip UTF-8 BOM at the start of the file62 if (n >= 3 && !memcmp(buf, "\xEF\xBB\xBF", 3)) {63 p += 3;64 n -= 3;65 }66 at_file_start = 0;67 }6869 if (raw) {70 data = jv_string_append_buf(data, p, n);71 if (!jv_is_valid(data))72 break;73 } else {74 jv_parser_set_buf(parser, p, n, !feof(file));75 jv value;76 while (jv_is_valid((value = jv_parser_next(parser))))77 data = jv_array_append(data, value);78 if (jv_invalid_has_msg(jv_copy(value))) {79 jv_free(data);80 data = value;81 break;82 }83 jv_free(value);84 }85 }86 if (!raw)87 jv_parser_free(parser);88 int badread = ferror(file);89 if (fclose(file) != 0 || badread) {90 jv_free(data);91 return jv_invalid_with_msg(jv_string_fmt("Error reading from %s",92 filename));93 }94 return data;95}