Example 1. Reading /etc/passwd
The following example uses csv(3m) to parse the /etc/passwd file and print the username and uid of each user.
#include <stdlib.h> #include <stdio.h> #include <mba/csv.h> int main(void) { FILE *in; unsigned char buf[1024]; unsigned char *row[10]; int n; in = fopen("/etc/passwd", "r"); while ((n = csv_row_fread(in, buf, 1024, row, 10, ':', CSV_TRIM)) > 0) { printf("%s %s\n", row[0], row[2]); } fclose(in); return EXIT_SUCCESS; }
Please note that escaping a quote requires that the entire element be quoted as well. So a quoted string element would actually look like """foo""" where the outer quotes quote the element and the remaining quote pairs are each an escape followed by the literal quote. This is consistent with how popular spreadsheets behave and deviating from this behavior will generate an error.
The csv_row_parse function
Description
#include <mba/csv.h> int csv_row_parse(const tchar *src, size_t sn, tchar *buf, size_t bn, tchar *row[], int rn, int sep, int flags)
The flags parameter can be zero or any combination of CSV_TRIM and CSV_QUOTES. If CSV_TRIM is specified, strings will be trimmed of leading and trailing whitespace (but an unquoted carriage-return before a newline is always trimmed regardless). If the CSV_QUOTES flag is spcecified, quotes will be interpreted. Both flags should be specified when parsing conventional CSV files.
The csv_row_parse function is actually a macro for either csv_row_parse_str or csv_row_parse_wcs. The csv_row_parse_wcs function has the same prototype but accepts wchar_t parameters whereas csv_row_parse_str accepts unsigned char parameters.
The csv_row_fread function
Description
#include <mba/csv.h> int csv_row_fread(FILE *in, unsigned char *buf, size_t bn, unsigned char *row[], int numcols, int sep, int flags)