Skip to content

Instantly share code, notes, and snippets.

@tijon1
Created May 22, 2023 13:33
Show Gist options
  • Save tijon1/255054e05b698af1a59250d6cf57fd0c to your computer and use it in GitHub Desktop.
Save tijon1/255054e05b698af1a59250d6cf57fd0c to your computer and use it in GitHub Desktop.
VBL parser
#include <iostream>
#include <map>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct VBLData
{
string fileName;
// Use a sequence-based container to handle the data because MSVC STD doesn't care about insertion order of multimaps
vector<pair<string, string>> data;
};
const std::string WHITESPACE = " \n\r\t\f\v";
std::string ltrim(const std::string& s)
{
size_t start = s.find_first_not_of(WHITESPACE);
return (start == std::string::npos) ? "" : s.substr(start);
}
std::string rtrim(const std::string& s)
{
size_t end = s.find_last_not_of(WHITESPACE);
return (end == std::string::npos) ? "" : s.substr(0, end + 1);
}
std::string trim(const std::string& s) {
return rtrim(ltrim(s));
}
size_t splitLine(const std::string& txt, std::vector<std::string>& strs, char ch)
{
size_t pos = txt.find(ch);
size_t initialPos = 0;
strs.clear();
// Decompose statement
while (pos != std::string::npos) {
strs.push_back(txt.substr(initialPos, pos - initialPos));
initialPos = pos + 1;
pos = txt.find(ch, initialPos);
}
// Add the last one
strs.push_back(txt.substr(initialPos, std::min(pos, txt.size()) - initialPos + 1));
return strs.size();
}
VBLData ParseFile(const char* filename)
{
// lets create the necessary classes for handling data
VBLData vblData;
vblData.data = {};
vblData.fileName = filename;
std::ifstream file(filename);
if (file.is_open())
{
string line;
vector<string> split;
while (getline(file, line))
{
// Trim line to remove all sorts of trailing, and leading spaces.
line = trim(line);
// Lets not continue if this is a comment or empty.
if (line.empty()) continue;
if (line.at(0) == '#') continue;
// do the magical split, output into a vector
splitLine(line, split, ' ');
// if the syntax is correct, work
if (!split.empty())
{
// key
// split[0]
// value
// split[1]
vblData.data.push_back(pair<string, string>(split[0], split[1]));
}
}
}
return vblData;
}
int main()
{
VBLData data = ParseFile("example.vbl");
for (const auto& b : data.data)
{
cout << "key " << b.first << " value " << b.second << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment