DataReelDataReelC++ Transition Guide

Examples › General Examples

general_config_class

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_general/config_class/testprog.cpp · Modern: examples_modern/general/config_class/modern.cpp

Modern equivalent of the gxConfig test program. The configuration file is read line by line with std::getline() into a std::map of names and values (std::string_view trims without copies). A lookup returns std::optional, so a missing setting and a setting of 0 are different (the legacy "if(!i1)" treats Int=0 as missing). Numbers are parsed with C++17 std::from_chars, which reports junk and overflow instead of returning 0. ChangeConfigValue() becomes set(): change the value in memory and write the whole file back through a temporary file and a rename, so a crash cannot leave half a file.

Run with the path of a config file (default gxconfig.ini, the legacy example's file). The program works on a copy, modern_config.ini.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
Find(), IFind(), FindLast()find(), a std::search with a case-folding predicate, rfind()C++98Watch out: rfind("") returns size(), where FindLast("") returns -1.
DeleteAt(), InsertAt(), ReplaceAt(), ReplaceString()erase(), insert(), replace(); std::replace for charactersC++98A count past the end is clamped; a position past the end throws std::out_of_range.
SetWidth(), SetFill(), Precision(), sprintf()std::format("{:*>10} {:.3f}", ...)C++20C++17 and older: <iomanip> setw, setfill, setprecision.
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
gxConfigstd::getline() into a std::map; std::optional lookups; std::from_charsC++17A rewrite through a temporary file and rename().

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/config_class/testprog.cpp 273 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include <stdio.h>
#include "gxconfig.h"

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

// Data structure use to store program gxConfiguration values
struct ProgramgxConfig
{
  ProgramgxConfig() { // Set the default values
    s_val1 = "YES";
    s_val2 = "NO";
    s_val3 = "TRUE";
    s_val4 = "FALSE";
    i_val = 32768;
    l_val = 2147483647;
    d_val = 1.12345;
  }
  ProgramgxConfig(const ProgramgxConfig &ob) {
    s_val1 = ob.s_val1;
    s_val2 = ob.s_val2;
    s_val3 = ob.s_val3;
    s_val4 = ob.s_val4;
    i_val = ob.i_val; l_val = ob.l_val; d_val = ob.d_val;
  }

  gxString s_val1;
  gxString s_val2;
  gxString s_val3;
  gxString s_val4;
  int i_val;
  long l_val;
  double d_val; 
};

void PausePrg()
{
  cin.get();
  cout << "Press enter to continue..." << "\n";
  cout << "\n";
}

void DisplayConfig(gxConfig *CfgData, ProgramgxConfig *cfg)
// Display the program gxConfiguration and load gxConfig values
{
  char *s1 = CfgData->GetStrValue("String1");
  if(!s1) {
    cout << "String1 section missing from gxConfig file" << "\n";
  }
  else {
    cout << "String1 section of gxConfig file = " << s1 << "\n";
    cfg->s_val1 = s1;
  }

  char *s2 = CfgData->GetStrValue("String2");
  if(!s2) {
    cout << "String2 section missing from gxConfig file" << "\n";
  }
  else {
    cout << "String2 section of gxConfig file = " << s2 << "\n";
    cfg->s_val2 = s2;
  }

  char *s3 = CfgData->GetStrValue("String3");
  if(!s3) {
    cout << "String3 section missing from gxConfig file" << "\n";
  }
  else {
    cout << "String3 section of gxConfig file = " << s3 << "\n";
    cfg->s_val3 = s3;
  }

  char *s4 = CfgData->GetStrValue("String4");
  if(!s4) {
    cout << "String4 section missing from gxConfig file" << "\n";
  }
  else {
    cout << "String4 section of gxConfig file = " << s4 << "\n";
    cfg->s_val4 = s4;
  }

  int i1 = CfgData->GetIntValue("Int");
  if(!i1) {
    cout << "Int section missing from gxConfig file" << "\n";
  }
  else {
    cout << "Integer section of gxConfig file = " << i1 << "\n";
    cfg->i_val = i1;
  }

  double d1 = CfgData->GetFloatValue("Float");
  if(!d1) {
    cout << "Float section missing from gxConfig file" << "\n";
  }
  else {
    cout << "Floating Point number section of gxConfig file = "
	 << d1 << "\n";
    cfg->d_val = d1;
  }
  
  long l1 = CfgData->GetLongValue("Long");
  if(!l1) {
    cout << "Long int section missing from gxConfig file" << "\n";
  }
  else {
    cout << "Long int section of gxConfig file = " << l1 << "\n";
    cfg->l_val = l1;
  }

  cout << "\n";
}

void MultipleRead(gxConfig *CfgData)
{
  char *ServerName = CfgData->GetStrValue("ServerName");
  if(!ServerName) {
    cout << "ServerName value is not set in the gxConfig file" << "\n";
    return;
  }
  else
    cout << "Server name = " << ServerName << "\n";
  
  char *FullPathName = CfgData->GetStrValue("FullPathName0");
  if(!FullPathName) {
    cout << "No path names are set in the gxConfig file" << "\n";
    return;
  }

  char cfgValue[255];
  long file_num = -1;
  
  while(1) {
    file_num++;
    sprintf(cfgValue, "FullPathName%d", (int)file_num);
    char *buf = CfgData->GetStrValue(cfgValue);
    if(!buf) break;

    gxString sbuf(buf);
    int offset = 0;
    int index = 0;
    while(1) {
    offset = sbuf.Find("/", offset);
    if(offset != -1) index = offset;
    if(offset == -1) break;
    offset++;
    }
    if(index > 0) sbuf.DeleteAt(0, ++index);

    if(sbuf.length() == 0) {
      cout << "Invalid file name for " << cfgValue << "\n";
      return;
    }
    
    cout << "Reading: " << buf << "\n";
    cout << "Copying to: " << sbuf.c_str() << "\n";

    buf = 0;
    for(int i = 0; i < 255; i++) cfgValue[i] = 0;
  }
  cout << "\n";
}

void NewParmID(gxConfig *CfgData)
{
  CfgData->UnLoad();
  CfgData->SetParmID("://");
  gxString parmName("http");
  CfgData->ReadComments();
  CfgData->ReLoad();
  
  gxConfigListNode *ptr = (gxConfigListNode *)CfgData->GetHead();
  while(ptr) { // Scan until end of list
    int offset = 0;
    offset = ptr->node_data.Find(parmName);
    if(offset != -1) {
      gxConfigListNode *sptr = (gxConfigListNode *)ptr->next;
      gxString ServerName(sptr->node_data);
      gxString FullPathName(sptr->node_data);
      offset = ServerName.Find("/");
      if(offset != -1) {
	ServerName.DeleteAt(offset, (ServerName.length() - offset));
	FullPathName.DeleteAt(0, offset);
	cout << "Server: " << ServerName.c_str() << " Path: "
	     << FullPathName.c_str() << "\n";
      }
    }
    ptr = (gxConfigListNode *)ptr->next;
  }
}

int main()
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  gxConfig *CfgData = new gxConfig;
  ProgramgxConfig *cfg = new ProgramgxConfig;
  int Status;

  // Test for all three overloads
  const char *fname = "gxconfig.ini";
  
  cout << "Loading gxConfig File..." << "\n";
  Status = CfgData->Load(fname);
  if(!Status) {
    cout << "gxConfig file not found!" << "\n";
    delete CfgData;
    delete cfg;
    return 0;
  }
  else
    cout << "Processing file: " << CfgData->GetFileName() << "\n";

  DisplayConfig(CfgData, cfg);
  ProgramgxConfig org_gxConfig(*cfg); // Record the original values
  
  cout << "Testing reload function" << "\n";
  PausePrg();
  CfgData->ReLoad(fname);
  DisplayConfig(CfgData, cfg);

  cout << "Writing new values to the file" << "\n";
  PausePrg();
  CfgData->ChangeConfigValue("String1", "no");
  CfgData->ChangeConfigValue("String2", "yes");
  CfgData->ChangeConfigValue("String3", "false");
  CfgData->ChangeConfigValue("String4", "true");
  
  CfgData->ChangeConfigValue("Float", 1.98712);
  CfgData->ChangeConfigValue("Int", 12345);
  CfgData->ChangeConfigValue("Long", 23889);
  DisplayConfig(CfgData, cfg);
  
  cout << "Restoring original values" << "\n";
  PausePrg();
  CfgData->ChangeConfigValue("String1", org_gxConfig.s_val1);
  CfgData->ChangeConfigValue("String2", org_gxConfig.s_val2);
  CfgData->ChangeConfigValue("String3", org_gxConfig.s_val3);
  CfgData->ChangeConfigValue("String4", org_gxConfig.s_val4);
  CfgData->ChangeConfigValue("Int", org_gxConfig.i_val);
  CfgData->ChangeConfigValue("Float", org_gxConfig.d_val);
  CfgData->ChangeConfigValue("Long", org_gxConfig.l_val);
  DisplayConfig(CfgData, cfg);

  cout << "Performing a multiple read and parsing operation" << "\n";
  PausePrg();
  MultipleRead(CfgData);

  cout << "Reloading the file with a new parameter ID string" << "\n";
  PausePrg();
  NewParmID(CfgData);
  
  CfgData->UnLoad();

  delete CfgData;
  delete cfg;
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/config_class/modern.cpp 150 lines
#include <charconv>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>

namespace fs = std::filesystem;

std::string_view trim(std::string_view s)
{
  auto b = s.find_first_not_of(" \t\r");
  if(b == std::string_view::npos) return {};
  return s.substr(b, s.find_last_not_of(" \t\r") - b + 1);
}

class Config {
public:
  bool load(const fs::path &file) {
    std::ifstream in(file);
    if(!in) return false;
    file_ = file;
    lines_.clear();
    for(std::string line; std::getline(in, line);) lines_.push_back(line);
    return true;
  }

  // The value of a name, or nothing if the name is not set
  std::optional<std::string> get(std::string_view name) const {
    for(const auto &line : lines_) {
      std::string_view v(line);
      if(trim(v).empty() || trim(v)[0] == '#') continue;
      auto eq = v.find('=');
      if(eq != std::string_view::npos && trim(v.substr(0, eq)) == name)
        return std::string(trim(v.substr(eq + 1)));
    }
    return std::nullopt;
  }

  template <class T>
  std::optional<T> get_number(std::string_view name) const {
    auto s = get(name);
    if(!s) return std::nullopt;
    T value{};
    auto [p, ec] = std::from_chars(s->data(), s->data() + s->size(), value);
    if(ec != std::errc() || p != s->data() + s->size()) return std::nullopt;
    return value;
  }

  // Change one setting (the whole name only) and rewrite the file
  bool set(std::string_view name, std::string_view value) {
    if(value.find_first_of("\r\n") != std::string_view::npos) return false;
    for(auto &line : lines_) {
      std::string_view v(line);
      if(trim(v).empty() || trim(v)[0] == '#') continue;
      auto eq = v.find('=');
      if(eq != std::string_view::npos && trim(v.substr(0, eq)) == name) {
        line = std::string(name) + "=" + std::string(value);
        return save();
      }
    }
    return false;
  }
  template <class T, class = std::enable_if_t<std::is_arithmetic_v<T>>>
  bool set(std::string_view name, T value) {
    return set(name, std::string_view(std::to_string(value)));
  }

  const std::vector<std::string> &lines() const { return lines_; }

private:
  bool save() const {
    fs::path tmp = file_;
    tmp += ".tmp";
    {
      std::ofstream out(tmp, std::ios::trunc);
      for(const auto &line : lines_) out << line << "\n";
      if(!out) return false;
    }
    std::error_code ec;
    fs::rename(tmp, file_, ec);   // Replaces the file in one step
    return !ec;
  }
  fs::path file_;
  std::vector<std::string> lines_;
};

void display(const Config &cfg)
{
  for(auto name : {"String1", "String2", "String3", "String4"}) {
    auto v = cfg.get(name);
    std::cout << name << " = " << (v ? *v : "(missing)") << "\n";
  }
  if(auto i = cfg.get_number<int>("Int")) std::cout << "Int = " << *i << "\n";
  else std::cout << "Int missing or not a number\n";
  if(auto l = cfg.get_number<long>("Long")) std::cout << "Long = " << *l << "\n";
  if(auto d = cfg.get("Float")) std::cout << "Float = " << std::stod(*d) << "\n";
  std::cout << "\n";
}

int main(int argc, char **argv)
{
  fs::path source = argc > 1 ? argv[1] : "gxconfig.ini";
  const fs::path fname = "modern_config.ini";
  std::error_code ec;
  fs::copy_file(source, fname, fs::copy_options::overwrite_existing, ec);
  if(ec) { std::cout << "Cannot copy " << source << ": " << ec.message() << "\n"; return 1; }

  Config cfg;
  if(!cfg.load(fname)) { std::cout << "Config file not found!\n"; return 1; }
  std::cout << "Processing file: " << fname << "\n";
  display(cfg);

  std::cout << "Writing new values to the file\n";
  cfg.set("String1", "no");
  cfg.set("Int", 0);           // 0 is a value, not "missing"
  cfg.set("Float", 1.98712);
  cfg.set("Long", 23889L);
  cfg.load(fname);             // ReLoad()
  display(cfg);

  std::cout << "Multiple read: FullPathName0, FullPathName1, ...\n";
  for(int n = 0;; n++) {
    auto path = cfg.get("FullPathName" + std::to_string(n));
    if(!path) break;
    std::cout << "Reading: " << *path << "  file name: "
              << fs::path(*path).filename().string() << "\n";
  }

  std::cout << "\nLines with a \"://\" parameter ID\n";
  for(const auto &line : cfg.lines()) {
    auto pos = line.find("://");
    if(pos == std::string::npos || line[0] == '#') continue;
    std::string_view rest = std::string_view(line).substr(pos + 3);
    auto slash = rest.find('/');
    std::cout << "Server: " << rest.substr(0, slash) << " Path: "
              << (slash == std::string_view::npos ? "/" : rest.substr(slash))
              << "\n";
  }
  fs::remove(fname);
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target general_config_class
./build-modern/general_config_class
# or without CMake:
g++ -std=c++17 -pthread -o general_config_class examples_modern/general/config_class/modern.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Processing file: "modern_config.ini"
String1 = YES
String2 = NO
String3 = TRUE
String4 = FALSE
Int = 32768
Long = 2147483647
Float = 1.1

Writing new values to the file
String1 = no
String2 = NO
String3 = TRUE
String4 = FALSE
Int = 0
Long = 23889
Float = 1.98712

Multiple read: FullPathName0, FullPathName1, ...
Reading: /home1/webpages/index.html  file name: index.html
Reading: /home1/webpages/images/brick.jpg  file name: brick.jpg
Reading: /home3/mail_list/list_add.htm  file name: list_add.htm
Reading: /home3/mail_list/list_remove.htm  file name: list_remove.htm
Reading: /home1/webpages/images/button_bar.jpg  file name: button_bar.jpg
Reading: /pub/docs/release_notes/mod1.txt  file name: mod1.txt
Reading: /pub/docs/release_notes/mod2.txt  file name: mod2.txt
Reading: /pub/docs/release_notes/mod3.txt  file name: mod3.txt

Lines with a "://" parameter ID
Server: www.myserver.net Path: /home1/webpages/index.html
Server: www.myserver.net Path: /home1/webpages/images/brick.jpg
Server: www.myserver.net Path: /home3/mail_list/list_add.htm
Server: www.myserver.net Path: /home3/mail_list/list_remove.htm
Server: www.myserver.net Path: /home1/webpages/images/button_bar.jpg
Server: www.myserver.net Path: /pub/docs/release_notes/mod1.txt
Server: www.myserver.net Path: /pub/docs/release_notes/mod2.txt
Server: www.myserver.net Path: /pub/docs/release_notes/mod3.txt