aboutsummaryrefslogtreecommitdiff
path: root/csv-tutorial.c
blob: 9bdb7e6a8deb55e843158cd424e3cab25055625c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <setjmp.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#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;
}