a firstworks project
Rudiments
About Documentation Download Licensing News

Using the csvsax class

The csvsax class provides a callback-based framework for parsing CSV data. When it encounters a column header, field, or record boundary, it calls one of its callback methods. These methods may be overridden by a child class to perform specific tasks. The csvsax class is especially useful if you can't afford to load the entire file into memory and use the csvdom class, or if you just need to extract specific data from a CSV file.

The quote and delimiter characters can be configured using setQuote() and setDelimiter(). By default, the quote character is a double-quote and the delimiter is a comma.

The following example creates a child class of csvsax that overrides the headerStart(), column(), headerEnd(), recordStart(), field(), and recordEnd() callback methods to print information about each CSV component encountered during parsing.

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

// create a csv sax handler by inheriting from csvsax
class mycsvhandler : public csvsax {

	protected:

		bool headerStart() {
			stdoutput.write("header:\n");
			return true;
		}

		bool column(const char *name, bool quoted) {
			stdoutput.printf("  column: %s",name);
			if (quoted) {
				stdoutput.write(" (quoted)");
			}
			stdoutput.write('\n');
			return true;
		}

		bool headerEnd() {
			stdoutput.write('\n');
			return true;
		}

		bool recordStart() {
			stdoutput.write("record:\n");
			return true;
		}

		bool field(const char *value, bool quoted) {
			stdoutput.printf("  field: %s",value);
			if (quoted) {
				stdoutput.write(" (quoted)");
			}
			stdoutput.write('\n');
			return true;
		}

		bool recordEnd() {
			stdoutput.write('\n');
			return true;
		}
};

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

	mycsvhandler	handler;

	// parse a csv string
	stdoutput.write("parsing csv:\n\n");
	handler.parseString(
		"\"name\",\"type\",\"legs\",\"domestic\"\n"
		"\"dog\",\"mammal\",\"4\",\"yes\"\n"
		"\"eagle\",\"bird\",\"2\",\"no\"\n"
		"\"snake\",\"reptile\",\"0\",\"no\"\n");
}
Copyright 2017 - David Muse - Contact