All my searching has yielded little in terms of C++ solutions....
I have a class that gets info out of config files, I have a static function that gets the site number out of a different config file. To avoid duplicating the code I create an instance of the class inside of the static function. This compiles without any warnings (with -Wall).
Unfortunately I can't find any information on whether or not it's undefined behavior. Is it ?
#include <iostream>
#include <fstream>
#include "srxDSLog.H"
extern SrxDsLog *Logger;
class Stanza {
private:
std::string config_file_path_;
public:
Stanza(std::string config_file_path) {
config_file_path_ = config_file_path;
}
std::string GetValue(std::string config_section, std::string config_setting) {
std::ifstream config_file(config_file_path_.c_str(), std::ios::in);
std::string current_section, line;
for ( ; std::getline(config_file, line); ) {
line = rtrim(line);
if (line.find(" ") == std::string::npos && line.find(":") != std::string::npos) {
current_section = line.substr(0, line.find(":"));
continue;
}
if (current_section == config_section) {
if (line.find(config_setting) != std::string::npos && line.find("=") != std::string::npos) {
return line.substr(line.find(config_setting) + config_setting.length() + 3); // we're getting the string starting after the name of the setting + " = " + 1. We're assuming there's exactly 1 space
}
}
}
if (current_section.empty()) {
Logger->WriteLog("Couldn't find section: " + config_section, LOG_ERROR, "Stanza::GetValue");
return "";
}
else {
Logger->WriteLog("Couldn't find setting: " + config_setting, LOG_ERROR, "Stanza::GetValue");
return "";
}
Logger->WriteLog("Somehow reached the end of function without returning", LOG_ERROR, "Stanza::GetValue");
return "";
}
static std::string rtrim(std::string input) {
if (input.find_last_not_of(" ") == input.length() - 1) {
return input;
}
else {
return input.substr(0, input.find_last_not_of(" ") + 1);
}
}
static int GetStoreNumber() {
Stanza store_config("/u/data/store.cfg");
std::string store_number = store_config.GetValue("store", "site");
return atoi(store_number.c_str());
}
};