DataReelDataReelC++ Transition Guide

Examples › General Examples

general_html_parser

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

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

Modern equivalent of the gxsHTML test. The standard library has no HTML parser, and HTML is not a regular language, so std::regex is the wrong tool for whole pages. What the standard library does give is a fast, copy-free way to scan text: std::string_view. This program reads a page into a std::string (one read, no fixed buffers), walks it with string_view to list the tags, and counts the scripts and style sheets, like gxsHTML's tag, script and style sheet lists. Comments and the inside of <script> and <style> are skipped. For real-world HTML in production use an HTML5 parser library (for example gumbo or lexbor), or keep gxsHTML.

Usage: modern file.html ... (with no arguments it scans a built-in page).

Legacy calls in this program

LegacyModern C++StandardNotes
gxList, gxListNodestd::list; splice() for MoveBefore()/MoveAfter()C++98The list owns its nodes: no DestroyList()/DestroyArrayList().
MemoryBufferstd::vector<unsigned char> or std::vector<std::byte>; std::span for viewsC++98 / C++17 / C++20std::search finds a byte pattern; std::fill for MemSet().
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/html_parser/testprog.cpp 250 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 <stdlib.h>
#include "gxshtml.h"
#include "gxs_ver.h"

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

// Version number and program name
const double ProgramVersionNumber = gxSocketVersion;
const char *ProgramName = "gxsHTML test program";

// Program globals
int parsing_tags = 0;
int listing_doc_tags = 0;
int listing_supported_tags = 0;

int CopyToMemory(const char *fname, MemoryBuffer &membuf)
{
  membuf.Clear();
  const unsigned buf_size = 1024;
  char sbuf[buf_size];
  DiskFileB f(fname);
  if(!f) return f.df_GetError();

  while(!f.df_EOF()) {
    if(f.df_Read((char *)sbuf, buf_size) != DiskFileB::df_NO_ERROR) {
      if(f.df_GetError() != DiskFileB::df_EOF_ERROR) 
	return f.df_GetError();
    }
    membuf.Cat((char *)sbuf, f.df_gcount());
  }

  f.df_Close();
  return 0;
}

void ParseTags(const char *fname)
{
  gxsHTML html;
  cout << "\n";
  cout << "Parsing " << fname << "\n";
  if(html.LoadHTMLFile(fname) != 0) {
    html.df_ExceptionMessage();
    return;
  }
  
  cout << "Found " << html.NumTags() << " tags" << "\n";

  cout << "\n";
  cout << "Parsing in-memory copy of " << fname << "\n";
  MemoryBuffer membuf;
  if(CopyToMemory(fname, membuf) != 0) {
    html.df_ExceptionMessage();
    return;
  }

  if(html.LoadMemoryBuffer(membuf) != 0) {
    cout << "A memory error occurred" << "\n";
    return;
  }
  cout << "Found " << html.NumTags() << " tags" << "\n";
  cout << "Found " << html.NumScripts() << " scripts" << "\n";
  cout << "Found " << html.NumStyleSheets() << " style sheets" << "\n";

  cout << "\n";
}

void PrintTagInfo(const gxsHTMLTagInfo &t)
{
  cout << "----- Tag's file information-----" << "\n";
  cout << "Tag file position (start): " << (long)t.start_tag << "\n";
  cout << "Tag file position (end):   " << (long)t.end_tag << "\n";
  cout << "Tag's total length <---->: " << t.tag_length << "\n";
  cout << "----- Tag Infomation ------" << "\n";
  cout << "Tag ID----: " << t.tag_id << "\n";
  cout << "Tag ------: " << t.tag.c_str() << "\n";
  cout << "Attributes: " << t.attr.c_str() << "\n";
  cout << "Original tag: " << t.tag_info.c_str() << "\n";

  cout << "----- Tag instructions -----" << "\n";
  if(t.start_instruction) cout << "Start of tag instruction" << "\n";
  if(t.end_instruction) cout << "End of tag instruction" << "\n";
  if(t.has_attributes) cout << "This tag has attributes associated with it"
			  << "\n";
  cout << "\n";
}

void ListSupportedTags()
{
  gxsHTML html;
  for(int i = 0; i < gxsMAX_SUPPORTED_TAGS; i++) {
    cout << "<" << html.GetTag(i) << ">" << "\n";
  }
}

void ListDocTags(const char *fname)
{
  gxsHTML html;
  html.LoadHTMLFile(fname);
  if(!html) {
    cout << "Could not open the " << fname << " file!" << "\n";
    return;
  }

  cout << "Found " << html.NumTags() << " tags" << "\n";
  cout << "Found " << html.NumScripts() << " scripts" << "\n";
  cout << "Found " << html.NumStyleSheets() << " style sheets" << "\n";
  cout << "Press enter to continue" << "\n";
  cin.get();

  gxList<gxsHTMLTagInfo> *tag_list = html.GetTagList();
  gxListNode<gxsHTMLTagInfo> *list_ptr = tag_list->GetHead();
  while(list_ptr) {
    PrintTagInfo(list_ptr->data);
    list_ptr = list_ptr->next; 
  }

  cout << "End of tags, listing scripts" << "\n";
  cout << "Press enter to continue" << "\n";
  cin.get();

  gxList<gxsScriptInfo> *script_list = html.GetScriptList();
  gxListNode<gxsScriptInfo> *script_ptr = script_list->GetHead();
  while(script_ptr) {
    cout << "\n";
    cout << script_ptr->data.script_code.c_str();
    cout << "\n";
    script_ptr = script_ptr->next; 
  }

  cout << "End scripts listing embedded style sheets" << "\n";
  cout << "Press enter to continue" << "\n";
  cin.get();

  gxList<gxsStyleInfo> *style_sheet_list = html.GetStyleSheetList();
  gxListNode<gxsStyleInfo> *style_sheet_ptr = style_sheet_list->GetHead();
  while(style_sheet_ptr) {
    cout << "\n";
    cout << style_sheet_ptr->data.style_code.c_str();
    cout << "\n";
    style_sheet_ptr = style_sheet_ptr->next; 
  }
}

void HelpMessage(const char *program_name, const double version_number)
{
  cout << "\n";
  cout.setf(ios::showpoint | ios::fixed);
  cout.precision(3);
  cout << "\n";
  cout << program_name << " version " << version_number  << "\n";
  cout << "Usage: " << program_name << " [switches] infile.html" << "\n";
  cout << "Example: " << program_name << " -l index.html" << "\n";
  cout << "Switches: " << "\n";
  cout << "          -l = List all the tags found in an HTML document." 
       << "\n";
  cout << "          -L = List all the tags supported by this program." 
       << "\n";
  cout << "          -p = Parse all the supported tags in an HTML document."
       << "\n";
  cout << "\n";
  return;
}

int ProcessArgs(char *arg)
{
  switch(arg[1]) {
    case 'l' :
      parsing_tags = 0;
      listing_doc_tags = 1;
      break;
      
    case 'L' :
      ListSupportedTags();
      return 0;

    case 'p' :
      parsing_tags = 1;
      listing_doc_tags = 0;
      break;

    default:
      cerr << "\n";
      cerr << "Unknown switch " << arg << "\n";
      cerr << "Exiting..." << "\n";
      cerr << "\n";
      return 0;
  }
  arg[0] = '\0';
  return 1; // All command line arguments were valid
}

// Program's main thread of execution.
// ----------------------------------------------------------- 
int main(int argc, char **argv)
// NOTE: None of the MSVC compilers will expand wildcard characters
// used in command-line arguments unless linked with the setargv.obj
// library. All the UNIX compilers will expand wildcard characters
// by default.
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  if(argc < 2) { 
    HelpMessage(ProgramName, ProgramVersionNumber);
    return 0;
  }
  
  // Process command ling arguments and files 
  int narg;
  char *arg = argv[narg = 1];

  while (narg < argc) {
    if(arg[0] != '\0') {
      if(arg[0] == '-') { // Look for command line arguments
	if(!ProcessArgs(arg)) return 0; // Exit if argument is not valid
      }
      else { 
	if(parsing_tags) {
	  ParseTags((const char *)arg);
	}
	else if(listing_doc_tags) {
	  ListDocTags((const char *)arg);
	}
	else {
	  cout << "No operation specified!" << "\n";
	  cout << "Exiting..." << "\n";
	}
      }
      arg = argv[++narg];
    }
  }

  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/html_parser/modern.cpp 98 lines
#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>

struct Tag {
  std::string name;        // Lower case, "/p" for an end tag
  std::string_view text;   // The whole tag, a view into the page
};

std::string lower(std::string_view s)
{
  std::string r(s);
  std::transform(r.begin(), r.end(), r.begin(),
                 [](unsigned char c) { return std::tolower(c); });
  return r;
}

std::vector<Tag> scan_tags(std::string_view page)
{
  std::vector<Tag> tags;
  std::size_t pos = 0;
  while((pos = page.find('<', pos)) != std::string_view::npos) {
    if(page.substr(pos, 4) == "<!--") {             // Skip a comment
      auto end = page.find("-->", pos + 4);
      if(end == std::string_view::npos) break;
      pos = end + 3;
      continue;
    }
    auto end = page.find('>', pos + 1);
    if(end == std::string_view::npos) break;         // Unclosed tag
    std::string_view text = page.substr(pos, end - pos + 1);
    std::string_view inner = text.substr(1, text.size() - 2);
    auto name_end = inner.find_first_of(" \t\r\n/>", inner[0] == '/' ? 1 : 0);
    Tag tag{lower(inner.substr(0, name_end)), text};
    pos = end + 1;
    if(tag.name.empty() || !(std::isalpha((unsigned char)tag.name[0]) ||
                             tag.name[0] == '/' || tag.name[0] == '!'))
      continue;                                      // "a < b" in text
    tags.push_back(tag);
    if(tag.name == "script" || tag.name == "style") { // Raw text element
      auto close = lower(page.substr(pos)).find("</" + tag.name);
      if(close == std::string::npos) break;
      pos += close;
    }
  }
  return tags;
}

void report(std::string_view label, std::string_view page)
{
  auto tags = scan_tags(page);
  std::map<std::string, int> counts;
  int scripts = 0, sheets = 0;
  for(const auto &t : tags) {
    counts[t.name]++;
    if(t.name == "script") scripts++;
    std::string attrs = lower(t.text);
    if(t.name == "style" ||
       (t.name == "link" && attrs.find("stylesheet") != std::string::npos))
      sheets++;
  }
  std::cout << label << ": " << tags.size() << " tags, " << scripts
            << " scripts, " << sheets << " style sheets\n";
  for(const auto &[name, n] : counts)               // C++17 structured binding
    std::cout << "  <" << name << "> x " << n << "\n";
}

int main(int argc, char **argv)
{
  if(argc > 1) {
    for(int i = 1; i < argc; i++) {
      std::ifstream in(argv[i], std::ios::binary);
      if(!in) { std::cout << "Cannot open " << argv[i] << "\n"; continue; }
      std::ostringstream ss;
      ss << in.rdbuf();                              // Whole file, any size
      report(argv[i], ss.str());
    }
    return 0;
  }
  const std::string page =
    "<!DOCTYPE html><html><head><title>Test</title>"
    "<link rel=\"stylesheet\" href=\"a.css\"><style>p { color: red }</style>"
    "<script>if (a < b && c > d) {}</script></head>"
    "<body><!-- <p>not a tag</p> --><p>One</p><p>Two &amp; three</p>"
    "<a href=\"x.html\">link</a><br/></body></html>";
  report("built-in page", page);
  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_html_parser
./build-modern/general_html_parser
# or without CMake:
g++ -std=c++17 -pthread -o general_html_parser examples_modern/general/html_parser/modern.cpp

Output of the modern program

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

built-in page: 21 tags, 1 scripts, 2 style sheets
  <!doctype> x 1
  </a> x 1
  </body> x 1
  </head> x 1
  </html> x 1
  </p> x 2
  </script> x 1
  </style> x 1
  </title> x 1
  <a> x 1
  <body> x 1
  <br> x 1
  <head> x 1
  <html> x 1
  <link> x 1
  <p> x 2
  <script> x 1
  <style> x 1
  <title> x 1