/* * Copyright (C) 2005 ? All rights reserved. * @date 2005/03/18 * @date 2005/09/09 * @author m */ #include #include "Properties.h" using std::string; Properties::Properties() : _properties() { } bool Properties::exists(const string& key) { return 0 < _properties.count(key); } string Properties::getProperty(string& key) { try { return _properties[key]; } catch (...) { return string(""); } } long Properties::setProperty(string& key, string& value) { try { _properties[key] = value; } catch (...) { return 1; } return 0; } long Properties::setProperty(string& key, int value) { char buffer[32] = {0}; ::snprintf(buffer, sizeof(buffer), "%d", value); try { _properties[key] = buffer; } catch (...) { return 1; } return 0; } string& Properties::operator[](const string& key) { return _properties[key]; } long Properties::parse(const char* filename) { if (filename == NULL) { return -1; } FILE* file = fopen(filename, "r"); if (!file) { return 2; } char buffer[1024]; string section; for (;;) { if (!fgets(buffer, 1024, file)) { break; } char* p = buffer; while (isspace(*p)) { p++; } if (*p == '[') { // it's a section title char* q = p+1; while (*q && *q != ']') { q++; } if (*q == ']' && q-p < 128) { *q = 0; section = p; } } else if (isalnum(*p)) { // it's a name or name=value char* q = p+1; while (*q && *q != '=' && *q != '#' && *q != '\n') { q++; } // point at end char* r = q; while ((p < r) && isspace(*(r-1))) { r--; } // remember if = was found if (*q == '=') { q++; } else { q = 0; } *r = 0; string name = p; string value; if (q) { while (isspace(*q)) { q++; } for (r = q; *r && *r != '#' && *r != '\n'; r++); while ((q < r) && isspace(*(r-1))) { r--; } if (q < r) { *r = 0; value = q; } } _properties[name] = value; } } fclose(file); return 0; } string Properties::toString() const { properties_t::const_iterator i; char buffer[1024]; string s; for (i = _properties.begin(); i != _properties.end(); i++) { ::snprintf( buffer, sizeof(buffer), "%-32s = %s\n", i->first.data(), i->second.data() ); s.append(buffer); } return s; }