From 7d956c533e9fd7d3bbb9a4a8b7f89f0fe54d4bc3 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Sun, 13 Apr 2025 22:43:46 +0200 Subject: first draft --- contrib/csv-tutorial.c | 106 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 contrib/csv-tutorial.c (limited to 'contrib/csv-tutorial.c') diff --git a/contrib/csv-tutorial.c b/contrib/csv-tutorial.c new file mode 100644 index 0000000..9bdb7e6 --- /dev/null +++ b/contrib/csv-tutorial.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include + +#include "csv.h" + +bool +processFile(const char *filename) +{ + FILE *in = fopen(filename, "r"); + + if ( in == NULL ) { + return false; + } + + csv_t csv; + csv_init(&csv); + + while ( csv_read(&csv, in) ) { + const size_t nfields = csv_nfields(&csv); + // ... + } + csv_cleanup(&csv); + + (void) fclose(in); + return true; +} + +bool +processFile_options(const char *filename) +{ + FILE *in = fopen(filename, "r"); + + if ( in == NULL ) { + return false; + } + + csv_options_t csv_options = csv_default_options; + csv_options.field_delimiter = '"'; + csv_options.field_separator = ','; + + csv_t csv; + csv_init_opt(&csv, &csv_options); + + while ( csv_read(&csv, in) ) { + const size_t nfields = csv_nfields(&csv); + // ... + } + csv_cleanup(&csv); + + (void) fclose(in); + return true; +} + +static void +csvErrorHandler(csv_err_t err, void *cb_arg) +{ + longjmp(*((jmp_buf *) cb_arg), err); +} + +bool +processFile_error(const char *filename) +{ + FILE *in = fopen(filename, "r"); + + if ( in == NULL ) { + return false; + } + + csv_options_t csv_options = csv_default_options; + csv_options.field_delimiter = '"'; + csv_options.field_separator = ','; + + jmp_buf env; + csv_options.cb_error = csvErrorHandler; + csv_options.cb_error_arg = &env; + + csv_t csv; + csv_init_opt(&csv, &csv_options); + + switch ( setjmp(env) ) { + case CSV_ERR_OK: + while ( csv_read(&csv, in) ) { + const size_t nfields = csv_nfields(&csv); + // ... + } + break; + + case CSV_ERR_OUT_OF_MEMORY: + case CSV_ERR_OUT_OF_RANGE: + case CSV_ERR_IO_READ: + case CSV_ERR_IO_WRITE: + csv_cleanup(&csv); + break; + } + + (void) fclose(in); + return true; +} + +int +main(void) +{ + return EXIT_SUCCESS; +} -- cgit v1.3