4 * Copyright (c) 2013 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.
23 #include "config-parser.h"
26 #define MAX_SECTION 64
27 #define WHITESPACE " \t"
28 #define NEWLINE "\n\r"
31 static inline char *trim_str(char *s)
35 s += strspn(s, WHITESPACE);
38 for (t = strchr(s, 0); t > s; t--)
39 if (!strchr(WHITESPACE, t[-1]))
45 int config_parse(const char *file_name, int cb(struct parse_result *result,
46 void *user_data), void *user_data)
49 struct parse_result result;
50 /* use stack for parsing */
52 char section[MAX_SECTION];
53 char *start, *end, *name, *value;
54 int lineno = 0, ret = 0;
56 if (!file_name || !cb) {
62 f = fopen(file_name, "r");
64 _E("Failed to open file %s", file_name);
69 /* parsing line by line */
70 while (fgets(line, MAX_LINE, f) != NULL) {
74 start[strcspn(start, NEWLINE)] = '\0';
75 start = trim_str(start);
77 if (*start == COMMENT) {
79 } else if (*start == '[') {
81 end = strchr(start, ']');
82 if (!end || *end != ']') {
88 strncpy(section, start + 1, sizeof(section));
89 section[MAX_SECTION-1] = '\0';
91 /* parse name & value */
92 end = strchr(start, '=');
93 if (!end || *end != '=') {
98 name = trim_str(start);
99 value = trim_str(end + 1);
100 end = strchr(value, COMMENT);
101 if (end && *end == COMMENT) {
103 value = trim_str(value);
106 result.section = section;
108 result.value = value;
109 /* callback with parse result */
110 ret = cb(&result, user_data);
117 _D("Success to load %s", file_name);
124 _E("Failed to read %s:%d!", file_name, lineno);