diff --git a/src/file_io.cpp b/src/file_io.cpp new file mode 100644 index 0000000..a5be9c3 --- /dev/null +++ b/src/file_io.cpp @@ -0,0 +1,66 @@ +#include "file_io.hpp" +#include "exceptions.hpp" +#include "util/string.hpp" + +#include +#include +#include +#include +#include + +namespace gz { + + template + bool writeKeyValueFile(const std::string& filepath, const std::unordered_map& content) { + bool success = false; + std::ofstream file(filepath.c_str()); + if (file.is_open()) { + file << "# Written by writeKeyValueFile" << std::endl; + for (std::pair line : content) { + file << line.first << " = " << line.second << std::endl; + } + file.close(); + success = true; + } + else { + throw FileIOError("Could not open file: '" + filepath + "'", "writeKeyValueFile"); + } + return success; + } + + std::unordered_map readKeyValueFile(const std::string& filepath, bool removeSpaces) { + std::unordered_map attr; + std::string line; + int eqPos; + std::ifstream file(filepath); + if (file.is_open()) { + while (file.good()) { + getline(file, line); + + // ignore commented lines + if (line.find("#") != std::string::npos) { continue; } + + // if "=" in line: split into key - value pair and store in map + if (line.find("=") != std::string::npos) { + if (removeSpaces) { // remove all whitespaces + line.erase(std::remove_if(line.begin(), line.end(), [](unsigned char x) { return std::isspace(x); }), line.end()); + } + else { // remove whitespaces until after equal sign + eqPos = line.find("="); + line.erase(std::remove_if(line.begin(), line.begin() + eqPos + 2, [](unsigned char x) { return std::isspace(x); }), line.begin() + eqPos + 2); + } + eqPos = line.find("="); + attr[line.substr(0, eqPos)] = line.substr(eqPos+1, line.length()); + } + } + file.close(); + } + else { + throw FileIOError("Could not open file: '" + filepath + "'", "readKeyValueFile"); + } + return attr; + } + + template bool writeKeyValueFile, std::equal_to>(const std::string&, const std::unordered_map, std::equal_to>&); + template bool writeKeyValueFile>(const std::string&, const std::unordered_map>&); +} diff --git a/src/file_io.hpp b/src/file_io.hpp new file mode 100644 index 0000000..b43ce67 --- /dev/null +++ b/src/file_io.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "util/string.hpp" +#include "util/string_conversion.hpp" + + +namespace gz { + + /** + * @brief Write a file that contains key = value pairs + * @details + * This template function is instantiated for the default unordered_map and the util::string_map from util/string.hpp + * @throws FileIOError + */ + template + bool writeKeyValueFile(const std::string& filepath, const std::unordered_map& content); + + /** + * @brief Read a file that contains key = value pairs + * @throws FileIOError + */ + std::unordered_map readKeyValueFile(const std::string& filepath, bool removeSpaces=false); + +}