Programming with Rudiments using the Utility Classes

Using the environment Class

The environment class allows you to get or set the value of environment variables. The following example gets, sets and resets the environment variable TEST.

@environment.C.html@ Using the commandline Class

Most programs take command line options in the option/value pair format:

program -option value -option value ...

or

program --option=value --option=value ...

The commandline class makes it easy to deal with command line options of either of these formats. Below is some code illustrating the use of the commandline class.

@commandline.C.html@ Using the parameterstring Class

Sometimes a function needs to take an arbitrary set of parameters. For example, a function for connecting to a database may need host, port, socket, username and password, any of which could be omitted depending on the database. Though C++ support methods which take an arbitrary number of parameters, sometimes it is more convenient to for the method to accept a single string parameter with name/value pairs in it instead.

The parameterstring class provides methods for parsing and accessing a parameter string of the following form:

name1='value1';name2='value2';name3='value3'

The single quotes are optional. If a parameter needs to contain a single quote, then it can be escaped as follows:

name='\'value\''

Backslashes can be similarly escaped:

name='\\value\\'
...
@parameterstring.C.html@ Using the datetime Class

One of the most difficult things to do in a Unix environment is deal with dates and times. The "standard" functions and structures associated with dates and times are complex, vary widely from platform to platform and in many cases are not thread safe. The datetime class attempts to rectify this situation.

The datetime class allows you to query and set the system clock. If your platform has a working real-time-clock (/dev/rtc), then you can query or set the hardware clock as well. Note that your program must run as root in order to set the system or hardware clock. Since it is common for the system clock to be set to the local time zone and the hardware clock to be set to GMT, a method is provided for converting the hardware clock time to the system's time zone.

Additionally there is a method for switching the time zone of the time currently represented in the class.

The datetime class also provides methods for converting between several common ways of representing time. Such as a formatted string, the number of seconds since 1970 and "struct tm".

There are also methods for adding discrete amounts of time to the time currently stored in the class. You can, for example add 150 seconds to "12:30:50 01/02/2003 EST" and get "12:32:20 01/02/2003 EST". You can add negative numbers to subtract time.

Below is some code illustrating the use of the datetime class.

@datetime.C.html@ Using the timezonefile Class

While I was working on timezone support in the datetime class I originally thought that it might be useful to be able to parse timezone files. I could not find any standard C functions for parsing them, so I wrote a class that parses them.

It turned out to be of very limited value, but it works and I never removed it. So, if you need such functionality, it exists.

@timezonefile.C.html@ Using the directory Class

@directory.C.html@ Using the filesystem Class

The filesystem class provides methods for collecting statistics about a filesystem. The "standard" function for getting filesystem statistics is either statfs or statvfs. Few operating systems implement statvfs and the structure returned by statfs varies greatly between operating systems. The filesystem class attempts to remedy this situation. However, no operating system supports every method in the filesystem class.

@filesystem.C.html@ Using the logger Class

The logger class and associated logdestination classes provide a framework for generating log messages from applications. An application can define a set of logdestinations and attach them to an instance of the logger class. Then, when the application calls one of the write() methods of the logger class, the log message is written to each of the logdestinations. For example, an application could simultaneously log to stderr and to a file. Currently stdout, stderr, file and syslog logdestinations are supported. If an application needs to send one set of log messages to one destination and another set to a different destinations, it can create two instances of the logger class and use one for each set of messages.

The following example illustrates use of the logger class.

@logger.C.html@ Using the permissions Class

The permissions class provides simple methods for generating permissions. The output of these methods can be used whenever a function takes an argument of type mode_t. Below is some code illustrating the use of the permissions class.

@permissions.C.html@ Using the randomnumber Class

Functions for generating random numbers vary from platform to platform. The randomnumber class attempts to rectify this situation. Below is some code illustrating the use of the randomnumber class.

@randomnumber.C.html@ Using the regularexpression Class

Regular expressions allow a programmer to perform complex string matching but methods for using regular expressions vary from platform to platform. The regularexpression class attempts to rectify this situation. Below is some code illustrating the use of the regularexpression class.

@regularexpression.C.html@ Using the chat Class

...

@chat.C.html@ Using the crypt Class

...

@crypt.C.html@ Using the dynamiclib Class

...

@dynamiclib.C.html@ Using the error Class

...

@error.C.html@ Using the intervaltimer Class

...

@intervaltimer.C.html@ Using the math Class

...

@math.C.html@ Using the mutex Class

...

@mutex.C.html@ Using the process Class

...

@process.C.html@ Using the serialportprofile Class

...

@serialportprofile.C.html@ Using the snooze Class

...

@snooze.C.html@ Using the Signal Classes

Signals allow processes to interrupt the execution of other processes. Signal handlers allow processes to intercept and react to the signals sent to them.

Rudiments provides 3 classes for working with signals: signalset, signalmanager and signalhandler.

A signalset is just a collection of signals. The signalset class allows a programmer to build up a collection of signals.

The signalmanager class provides methods for sending signals, ignoring signals, waiting for signals and examining blocked signals.

The signalhandler class provides methods for catching and handling signals.

Below is some code illustrating the use of all three classes. Note that you'll have to kill this program with a -9.

@signal.C.html@ Using the sharedmemory Class

Shared memory allows seperate processes to access a common block of memory. The standard functions and structures for managing shared memory segments are complex. The sharedmemory class attempts to rectify this situation. Below is some code illustrating the use of the sharedmemory class.

There are methods in the sharedmemory class that allow you to get and set user/group ownership and permissions of a segment that are not documented here, but they are straightforward and rarely used.

This program puts some data into shared memory then goes to sleep, giving another program time to access the segment.

@sharedmemory1.C.html@

This program reads the data from shared memory.

@sharedmemory2.C.html@ Using the semaphoreset Class

Semaphores allow seperate processes or threads to synchronize activities. The standard functions and structures for managing semaphores are complex. The sempahoreset class attempts to rectify this situation. Below is some code illustrating the use of the semaphoreset class.

There are methods in the semaphoreset class that allow you to get and set user/group ownership and permissions of a semaphore set that are not documented here, but they are straightforward and rarely used.

The first program prints out 1 and 3, the second program prints out 2 and 4. They use a set of 2 semaphores to synchronize these activities. No matter what order the programs are started in, they will always print out

1
2
3
4
1
2
3
4
etc.

These programs must both be run to the background.

@sharedmemory1.C.html@ @sharedmemory2.C.html@ Using the memorymap Class

...

@memorymap.C.html@ Using the memorypool Class

The memorypool class implements a pool of memory that starts with an initial buffer and grows dynamically as needed. Each time the pool is freed, the dynamic buffers are deallocated. After a configurable number of free's, the initial buffer is resized to the average amount of memory that was requested between free's since the last time it resized.

The memorypool class is especially useful for applications that do the same task over and over where varying amounts of memory are required during each iteration. The class is particularly efficient in cases where memory requirements are fairly constant between iterations with sporadic requirements for lots of memory or where the memory requirements steadily get larger or smaller across iterations.

Using a memorypool can be faster than allocating memory on demand, then deallocating it later and more efficient than using static buffers that are large enough to contain the largest possible data.

The following code connects to a server on the local machine and reads variable/value pairs from it.

@memorypool.C.html@ Using the variablebuffer Class

The variablebuffer class allows you to manipulate a buffer of arbitrary length containing binary data. You can append data to a variablebuffer or write data at arbitrary positions in the buffer.

@variablebuffer.C.html@ Using the stringbuffer Class

The stringbuffer class allows you to manipulate strings of arbitrary length. You can append data to a stringbuffer or write data at arbitrary positions in the buffer.

@stringbuffer.C.html@ Using the character Class

...

@character.C.html@ Using the charstring Class

The charstring class contains some commonly needed string manipulation and evaluation functions. Below is some code illustrating the use of the string class.

@charstring.C.html@ Using the rawbuffer Class

...

@rawbuffer.C.html@ Using the xmldom Class

The xmldom and xmldomnode classes provide a framework for DOM parsing of XML documents. The xmldom class provides methods for parsing the document and accessing it's root node. Each node of the document is represented by an instance of the xmldomnode class. The xmldomnode class provides methods for accessing a node's data, attributes, child nodes, parent nodes and sibling nodes. Since the xmldom class creates a representation of the XML document in memory, it should not be used to process arbitrarily large documents which could exhaust system memory.

The following XML file contains an address book.

<?xml version="1.0"?>
<!DOCTYPE instances SYSTEM "adbook.dtd">
<addressbook>
        <person firstname="David" middlename="Lee" lastname="Muse">
                <phones>
                        <phone location="home" number="1-222-333-4444"/>
                        <phone location="work" number="1-333-444-5555"/>
                        <phone location="mobile" number="1-444-555-6666"/>
                </phones>
                <addresses>
                        <address location="home" address="1234 homestreet dr." city="mycity" state="GA" zip="12345"/>
                        <address location="work" address="2345 workstreet dr." city="mycity" state="GA" zip="23456"/>
                </addresses>
                <emails>
                        <email location="home" address="dmuse@firstworks.com"/>
                        <email location="work" address="dmuse@workemail.com"/>
                </emails>
        </person>
</addressbook>

The following program parses the addressbook and prints it to the screen.

#include <rudiments/xmldom.h>
#include <iostream>

using namespace rudiments;
using namespace std;

int     main() {

        xmldom  x;
        x.parseFile("addressbook.xml");
        x.getRootNode()->cascadeOnDelete();


        xmldomnode      *addressbook=x.getRootNode()->getChild("addressbook");
        for (int i=0; i<addressbook->getChildCount(); i++) {

                xmldomnode      *person=addressbook->getChild(i);
                if (person->getType()!=TAG_XMLDOMNODETYPE) {
                        continue;
                }

                cout << person->getAttribute("firstname")->getValue() << " ";
                cout << person->getAttribute("middlename")->getValue() << " ";
                cout << person->getAttribute("lastname")->getValue() << endl;

                xmldomnode      *phones=person->getChild("phones");
                cout << "Phones:" << endl;
                for (int j=0; j<phones->getChildCount(); j++) {

                        xmldomnode      *phone=phones->getChild(j);
                        if (phone->getType()!=TAG_XMLDOMNODETYPE) {
                                continue;
                        }
                        cout << "       ";
                        cout << phone->getAttribute("location")->
                                                        getValue() << ": ";
                        cout << phone->getAttribute("number")->
                                                        getValue() << endl;
                }
                cout << endl;

                xmldomnode      *addresses=person->getChild("addresses");
                cout << "Addresses:" << endl;
                for (int j=0; j<addresses->getChildCount(); j++) {

                        xmldomnode      *address=addresses->getChild(j);
                        if (address->getType()!=TAG_XMLDOMNODETYPE) {
                                continue;
                        }
                        cout << "       ";
                        cout << address->getAttribute("location")->
                                                        getValue() << ": ";
                        cout << address->getAttribute("address")->
                                                        getValue() << " ";
                        cout << address->getAttribute("city")->
                                                        getValue() << ", ";
                        cout << address->getAttribute("state")->
                                                        getValue() << " ";
                        cout << address->getAttribute("zip")->
                                                        getValue() << endl;
                }
                cout << endl;

                xmldomnode      *emails=person->getChild("emails");
                cout << "Emails:" << endl;
                for (int j=0; j<emails->getChildCount(); j++) {

                        xmldomnode      *email=emails->getChild(j);
                        if (email->getType()!=TAG_XMLDOMNODETYPE) {
                                continue;
                        }
                        cout << "       ";
                        cout << email->getAttribute("location")->
                                                        getValue() << ": ";
                        cout << email->getAttribute("address")->
                                                        getValue() << endl;
                }
                cout << endl;
        }
}

Here is the output of the program above.

David Lee Muse
Phones:
        home: 1-222-333-4444
        work: 1-333-444-5555
        mobile: 1-444-555-6666

Addresses:
        home: 1234 homestreet dr. mycity, GA 12345
        work: 2345 workstreet dr. mycity, GA 23456

Emails:
        home: dmuse@firstworks.com
        work: dmuse@workemail.com
Using the xmlsax Class

The xmlsax class provides a callback-based framework for parsing XML documents. The xmlsax class provides methods for parsing strings of XML or XML files. When it encounters a tag, attribute or other XML component, it calls one of it's callback methods. These methods may be overridden by a child class to perform specific tasks. The xmlsax class is especially useful if you can't afford to load the entire document into memory and use the xmldom class, or if you just need to extract specific data from an XML file.

// Copyright (c) 2002  David Muse
// See the file COPYING for more information

#include <rudiments/xmlsax.h>
#include <stdio.h>

using namespace rudiments;

class myxmlsax : public xmlsax {
        public:
                        myxmlsax();
        private:
                int     xmlVersionStart();
                int     xmlVersionEnd();
                int     doctypeStart(char *name);
                int     externalSubset(char *filename);
                int     doctypeEnd();
                int     tagStart(char *name);
                int     attributeName(char *name);
                int     attributeValue(char *value);
                int     text(char *string);
                int     tagEnd(char *name);
                int     comment(char *string);
                int     cdata(char *string);
                void    indent(int spaces);
                int     ind;
};

myxmlsax::myxmlsax() : xmlsax() {
        ind=0;
}

int     myxmlsax::xmlVersionStart() {
        printf("XML version start:\n");
        return 1;
}

int     myxmlsax::xmlVersionEnd() {
        printf("XML version end:\n");
        return 1;
}

int     myxmlsax::doctypeStart(char *name) {
        printf("DOCTYPE start: %s\n",name);
        return 1;
}

int     myxmlsax::externalSubset(char *filename) {
        printf("        external subset: %s\n",filename);
        return 1;
}

int     myxmlsax::doctypeEnd() {
        printf("DOCTYPE end:\n");
        return 1;
}

void    myxmlsax::indent(int spaces) {
        for (int i=0; i<spaces; i++) {
                printf("  ");
        }
}

int     myxmlsax::tagStart(char *name) {
        indent(ind);
        printf("tagStart: %s\n",name);
        ind++;
        return 1;
}

int     myxmlsax::attributeName(char *name) {
        indent(ind+1);
        printf("attribute name: %s\n",name);
        return 1;
}

int     myxmlsax::attributeValue(char *value) {
        indent(ind+1);
        printf("attribute value: %s\n",value);
        return 1;
}

int     myxmlsax::text(char *string) {
        indent(ind+1);
        printf("text: \n%s\n",string);
        return 1;
}

int     myxmlsax::tagEnd(char *name) {
        ind--;
        indent(ind);
        printf("tagEnd: %s\n",name);
        return 1;
}

int     myxmlsax::comment(char *string) {
        indent(ind);
        printf("comment: \n%s\n",string);
        return 1;
}

int     myxmlsax::cdata(char *string) {
        indent(ind);
        printf("cdata: \n%s\n",string);
        return 1;
}


int main(int argv, const char **argc) {

        myxmlsax        x;
        x.parseFile("xmls.xml");
}
Using the dtd Class

The dtd class provides methods for parsing an XML DTD. The result is an XML DOM tree representing the DTD. Once parsed, the tree can be accessed using the xmldom and xmldomnode classes.

// Copyright (c) 2002  David Muse
// See the file COPYING for more information

#include <rudiments/dtd.h>
#include <stdio.h>

using namespace rudiments;

int main(int argv, const char **argc) {

        // display the contents of dtd.dtd
        dtd     d;
        d.parseFile("dtd.dtd");
        printf("%s\n",d.xml()->xml()->getString());
}
Using the passwdentry Class

The passwdentry class allows you to look up entries from /etc/passwd or from elsewhere if you're using the Name Service Switch.

@passwdentry.C.html@ Using the shadowentry Class

The shadowentry class allows you to look up entries from /etc/shadow or from elsewhere if you're using the Name Service Switch.

@shadowentry.C.html@ Using the groupentry Class

The groupentry class allows you to look up entries from /etc/group or from elsewhere if you're using the Name Service Switch.

@groupentry.C.html@ Using the hostentry Class

The hostentry class allows you to look up entries from /etc/hosts or from elsewhere if you're using the Name Service Switch.

@hostentry.C.html@ Using the protocolentry Class

The protocolentry class allows you to look up entries from /etc/protocols or from elsewhere if you're using the Name Service Switch.

@protocolentry.C.html@ Using the serviceentry Class

The serviceentry class allows you to look up entries from /etc/services or from elsewhere if you're using the Name Service Switch.

@serviceentry.C.html@ Using the rpcentry Class

The rpcentry class allows you to look up entries from /etc/rpc or from elsewhere if you're using the Name Service Switch.

@rpcentry.C.html@ Using the linkedlist Class

The linkedlist class allows you to store arbitrary data in a doubly-linked list.

Since lists of strings are commonly used, a stringlist typedef is provided for convenience.

@linkedlist.C.html@ Using the dictionary Class

The dictionary class allows you to store arbitrary key/value-pair data.

Since dictionaries with string and long integer keys and dictionaries with string keys and values are commonly used, convenience classes are provided for each.

@dictionary.C.html@