1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| bool load_config_file(Configuration& config, FILE* config_file, JSON_ERROR& parser_error) {
if (config_file == NULL) {
std::printf("load_config_file - json file is not opened\n");
return false;
}
unsigned char* str = NULL;
unsigned char* tmp_str;
size_t size = 0, index;
int c;
bool is_ok = true, can_continue = true;
// Load file
while(is_ok && can_continue) {
tmp_str = (unsigned char*) realloc(str, (size + 512 /** sizeof(unsigned char)*/));
if (tmp_str != NULL) {
str = tmp_str;
can_continue = 1;
index = 0;
do {
c = getc (config_file);
if (c != EOF) {
str[size + index] = (unsigned char) c;
++index;
} else {
str[size + index] = '\0';
can_continue = 0;
}
} while(can_continue && (index < 512));
size += 512;
} else {
CLEAN_STR
std::printf("load_config_file - cannot realloc str\n");
is_ok = false;
}
}
fclose(config_file);
if (!is_ok) { return false; }
// Remove UTF-8 BOM
if ((((unsigned char) str[0]) == 0xEF) && (size > 3)) {
if (((unsigned char) str[1]) == 0xBB) {
if (((unsigned char) str[2]) == 0xBF) {
str[0] = ' ';
str[1] = ' ';
str[2] = ' ';
} else {
is_ok = false;
parser_error = JSON_ERR_INVALID_BOM;
}
} else {
is_ok = false;
parser_error = JSON_ERR_INVALID_BOM;
}
} else {
if (size <= 3) { parser_error = JSON_ERR_INVALID_SIZE; is_ok = false; }
}
IS_NOT_OK_CLEAN_STR_RETURN
// Parse json
json_error_t error;
json_t* root = json_loads((char*) str, 0, &error);
if (root != NULL) {
json_t* data = json_object_get(root, "product_name");
json_t* data_object;
json_t* value;
if ( json_is_string(data) ) {
size = json_string_length(data);
if (size > 30) { size = 30; }
_snprintf(((char*) config.product_name), size, json_string_value(data));
config.product_name[size] = '\0';
} else {
is_ok = false;
parser_error = JSON_ERR_MISSING_PRODUCT_NAME;
}
IS_NOT_OK_CLEAN_STR_RETURN
data = json_object_get(root, "id");
if ( json_is_integer(data) ) {
config.id = (unsigned long) json_integer_value(data);
} else {
is_ok = false;
parser_error = JSON_ERR_MISSING_ID;
}
IS_NOT_OK_CLEAN_STR_RETURN
// ...
IS_NOT_OK_CLEAN_STR_RETURN
} else {
is_ok = false;
std::printf("error at line %d, column, %d\nText: %s\nSource: %s\n\n", error.line, error.column, error.text, error.source);
parser_error = JSON_ERR_LOAD_ROOT;
}
CLEAN_STR
return is_ok;
} |
Partager