4 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
6 * Licensed under the Apache License, Version 2.0 (the License);
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
22 #include "ini-parser.h"
24 #include "shared/log.h"
27 #define MAX_SECTION 64
28 #define WHITESPACE " \t"
29 #define NEWLINE "\n\r"
32 static inline char *trim_str(char *s)
36 s += strspn(s, WHITESPACE);
39 for (t = strchr(s, 0); t > s; t--)
40 if (!strchr(WHITESPACE, t[-1]))
46 int config_parse(const char *file_name, int cb(struct parse_result *result,
47 void *user_data), void *user_data)
50 struct parse_result result;
51 /* use stack for parsing */
53 char section[MAX_SECTION];
54 char *start, *end, *name, *value;
55 int lineno = 0, ret = 0;
57 if (!file_name || !cb) {
63 f = fopen(file_name, "r");
65 _E("Failed to open file '%s'.", file_name);
70 /* parsing line by line */
71 while (fgets(line, MAX_LINE, f) != NULL) {
75 start[strcspn(start, NEWLINE)] = '\0';
76 start = trim_str(start);
78 if (*start == COMMENT) {
80 } else if (*start == '[') {
82 end = strchr(start, ']');
83 if (!end || *end != ']') {
89 strncpy(section, start + 1, sizeof(section)-1);
90 section[MAX_SECTION-1] = '\0';
92 /* parse name & value */
93 end = strchr(start, '=');
94 if (!end || *end != '=') {
99 name = trim_str(start);
100 value = trim_str(end + 1);
101 end = strchr(value, COMMENT);
102 if (end && *end == COMMENT) {
104 value = trim_str(value);
107 result.section = section;
109 result.value = value;
110 /* callback with parse result */
111 ret = cb(&result, user_data);
118 _D("Success to load '%s'.", file_name);
125 _E("Failed to read '%s': %d", file_name, lineno);