examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

commit f6636a139c4bc1c525fe9db4a1cc2eb07d4d4f50
parent b1cf63a36c74da863cb66b9aa9bb7e50b2dc76fe
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Fri, 14 Apr 2023 23:41:41 +0100

treeify: Add tool to treeify the output of find

Diffstat:
Asrc/treeify.cpp | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 99 insertions(+), 0 deletions(-)

diff --git a/src/treeify.cpp b/src/treeify.cpp @@ -0,0 +1,99 @@ +#include <iostream> +#include <sstream> +#include <iomanip> + +using namespace std; + +constexpr string_view space = " "; +constexpr string_view stem = "\u2502"; +constexpr string_view leaf = "\u2514"; +constexpr string_view branch = "\u251C"; + + +struct node +{ + string name; + node* parent = nullptr; + node* next_sibling = nullptr; + node* first_child = nullptr; + + node(string name) + : name(name) + {} + + auto operator <=>(string const& rhs) const + { + return name <=> rhs; + } + + ~node() + { + if (next_sibling) + delete next_sibling; + if (first_child) + delete first_child; + } +}; + +static void trunk(ostream& out, node* node) +{ + if (not node or not node->parent) + return; + trunk(out, node->parent); + out << (node->next_sibling ? stem : space); +} + +static ostream& operator <<(ostream& out, node* node) +{ + if (not node) + return out; + + trunk(out, node->parent); + if (node->parent) + out << (node->next_sibling ? branch : leaf); + if (node->first_child) + out << "\e[34;1m"; + out << node->name; + if (node->first_child) + out << "\e[m/"; + return out + << endl + << node->first_child + << node->next_sibling; +} + +int main() +{ + string line; + node* head = nullptr; + + while (getline(cin, line)) + { + istringstream in{line}; + string name; + node** current = &head; + node* parent = nullptr; + + while (getline(in, name, '/')) + { + while (*current && (*current)->name < name) + current = &(*current)->next_sibling; + if (*current && (*current)->name == name) + { + parent = *current; + current = &parent->first_child; + continue; + } + node* nod = new node{name}; + nod->next_sibling = *current; + nod->parent = parent; + *current = parent = nod; + current = &nod->first_child; + } + } + + cout << head; + + if (head) + delete head; +}