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(int argc, char *argv[]) { FILE *in; char buf[1024]; 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 whole element to 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 Excel and gnumeric 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. If the CSV_QUOTES flag is spcecified, quotes will be interpreted. Both flags should usually be specified although it is not uncommon to encounter tab delimited files where quotes should not be interpreted.
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, char *buf, size_t bn, char *row[], int numcols, int sep, int flags)