/* File: FileHelper.h Description: Provides utility functions for loading and saving records from and to CSV-like text files. Ensures files are created if missing and supports simple record persistence. Author: Trenser Date: 22-May-2026 */ #pragma once #include #include #include #include #include "Vector.h" namespace util { /* Function: ensureDirectoryExists Description: Creates all missing directories present in the given file path. Iteratively parses the path and creates each directory level using _mkdir() before file operations are performed. Parameters: - filePath: const std::string&, relative or absolute file path Returns: - void Throws: - None (_mkdir failures are intentionally ignored if directory already exists) */ inline void ensureDirectoryExists(const std::string& filePath) { size_t position = 0; while ((position = filePath.find('/', position)) != std::string::npos) { std::string directory = filePath.substr(0, position); if (!directory.empty()) { (void)_mkdir(directory.c_str()); } position++; } } /* Function: loadRecords Description: Loads records from a given file path into a vector of strings. Skips the header line if present. Creates the file if it does not exist. Parameters: - filePath: const std::string&, path to the file Returns: - util::Vector: Vector containing all records (excluding header) Throws: - None (creates file if missing) */ inline util::Vector loadRecords(const std::string& filePath) { util::Vector records; std::ifstream file(filePath); if (!file.is_open()) { ensureDirectoryExists(filePath); std::ofstream newFile(filePath); newFile.close(); file.open(filePath); } std::string line; bool isHeader = true; while (std::getline(file, line)) { if (isHeader) { isHeader = false; continue; } records.push_back(line); } return records; } /* Function: saveRecords Description: Saves records to a given file path. Overwrites existing content and writes a header line followed by all records. Parameters: - filePath: const std::string&, path to the file - records: const util::Vector&, vector of records to save Returns: - void Throws: - std::runtime_error if the file cannot be opened for writing */ inline void saveRecords(const std::string& filePath, const util::Vector& records) { std::ofstream file(filePath, std::ios::trunc); if (!file.is_open()) { throw std::runtime_error("Failed to open file " + filePath); } file << "Values" << '\n'; int numberOfRecords = records.getSize(); for (int index = 0; index < numberOfRecords; index++) { file << records[index] << '\n'; } } }