All pastes #74622 Raw Edit

Miscellany

public cpp v1 · immutable
#74622 ·published 2006-06-29 07:36 UTC
rendered paste body
#pragma warning(disable: 4786) #include "ini.h" #include <stdexcept>#include <fstream>#include <sstream>#include <string>#include <map> bool LoadIni(const char *filename, ini_t& out) {    // Open    std::ifstream in(filename, std::ios::in|std::ios::binary);     if (!in.is_open()) {        return false;    }     // Get length    in.seekg(0, std::ios::end);    int len = in.tellg();    in.seekg(0, std::ios::beg);     // Read everything    char *buffer = new char[len+1];    in.read(buffer, len);    buffer[in.gcount()] = '\0';     for (int i = 0; i < in.gcount(); i++) {        buffer[i] ^= 'n';    }     std::istringstream str_stream(buffer);    delete[] buffer;     // Close file    in.close();     // Iterate in lines    std::string line, section, item, value;    std::string::size_type pos;     for(int n = 1; std::getline(str_stream, line); n++) {        // Trim the line first, start by finding the first non-whitespace char        pos = line.find_first_not_of(" \t\r");         // If line is empty        if (pos == std::string::npos) {            continue;        }         // Trim it         line = line.substr(pos, line.find_last_not_of(" \t\r")-pos+1);         // See if this is a section specifier        if (line[0] == '[' && line[line.length()-1] == ']') {            section = line.substr(1, line.length()-2);            out[section] = ini_section_t();            continue;        }         // See if this line is an item        pos = line.find('=', 0);         if (pos != std::string::npos) {            // If section is not set yet, it's a parse error!            if (section.empty()) {                std::ostringstream str_error;                str_error << "Parse error in line " << n << ", expecting section";                throw std::runtime_error(str_error.str());            }             item = line.substr(0, pos);            value = line.substr(pos+1);            out[section][item] = value;            continue;        }         // No regular syntax match, so error!        std::ostringstream str_error;        str_error << "Parse error in line " << n;        throw std::runtime_error(str_error.str());    }     return true;}