13 vector<string> split_tokens(const string &line)
18 for (size_t i = 0; i < line.size(); ++i) {
19 if (isspace(line[i])) {
20 if (!current_token.empty()) {
21 ret.push_back(current_token);
23 current_token.clear();
25 current_token.push_back(line[i]);
28 if (!current_token.empty()) {
29 ret.push_back(current_token);
34 vector<string> split_lines(const string &str)
39 for (size_t i = 0; i < str.size(); ++i) {
40 // Skip \r if followed by an \n.
41 if (str[i] == '\r' && i < str.size() - 1 && str[i + 1] == '\n') {
45 // End of the current line?
47 if (!current_line.empty()) {
48 ret.push_back(current_line);
52 current_line.push_back(str[i]);
55 if (!current_line.empty()) {
56 ret.push_back(current_line);
61 vector<ConfigLine> parse_config(const string &filename)
63 vector<ConfigLine> ret;
65 FILE *fp = fopen(filename.c_str(), "r");
67 perror(filename.c_str());
73 if (fgets(buf, sizeof(buf), fp) == NULL) {
77 // Chop off the string at the first #, \r or \n.
78 buf[strcspn(buf, "#\r\n")] = 0;
80 // Remove all whitespace from the end of the string.
81 size_t len = strlen(buf);
82 while (len > 0 && isspace(buf[len - 1])) {
86 // If the line is now all blank, ignore it.
91 vector<string> tokens = split_tokens(buf);
92 assert(!tokens.empty());
95 line.keyword = tokens[0];
97 for (size_t i = 1; i < tokens.size(); ++i) {
98 // foo=bar is a parameter; anything else is an argument.
99 size_t equals_pos = tokens[i].find_first_of('=');
100 if (equals_pos == string::npos) {
101 line.arguments.push_back(tokens[i]);
103 string key = tokens[i].substr(0, equals_pos);
104 string value = tokens[i].substr(equals_pos + 1, string::npos);
105 line.parameters.insert(make_pair(key, value));
116 int fetch_config_int(const vector<ConfigLine> &config, const string &keyword, int min_limit, int max_limit)
118 bool value_found = false;
120 for (unsigned i = 0; i < config.size(); ++i) {
121 if (config[i].keyword != keyword) {
124 if (config[i].parameters.size() > 0 ||
125 config[i].arguments.size() != 1) {
126 fprintf(stderr, "ERROR: '%s' takes one argument and no parameters\n", keyword.c_str());
130 value = atoi(config[i].arguments[0].c_str()); // TODO: verify int validity.
133 fprintf(stderr, "ERROR: Missing '%s' statement in config file.\n",
137 if (value < min_limit || value > max_limit) {
138 fprintf(stderr, "ERROR: '%s' is set to %d, must be in [%d,%d]\n",
139 keyword.c_str(), value, min_limit, max_limit);