aboutsummaryrefslogtreecommitdiff
path: root/contrib/csv-tutorial.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2025-04-13 22:43:46 +0200
committerThomas Schmucker <ts@its1.de>2025-04-13 22:43:46 +0200
commit7d956c533e9fd7d3bbb9a4a8b7f89f0fe54d4bc3 (patch)
treeea1c5bc19dfe6bacad2d377378c460ee5284e74e /contrib/csv-tutorial.c
parent85fe3b67a67825dfc5e43959f001b2a7159dc23f (diff)
downloadlibcsv-7d956c533e9fd7d3bbb9a4a8b7f89f0fe54d4bc3.tar.gz
libcsv-7d956c533e9fd7d3bbb9a4a8b7f89f0fe54d4bc3.tar.bz2
libcsv-7d956c533e9fd7d3bbb9a4a8b7f89f0fe54d4bc3.zip
first draft
Diffstat (limited to 'contrib/csv-tutorial.c')
-rw-r--r--contrib/csv-tutorial.c106
1 files changed, 106 insertions, 0 deletions
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 @@
1#include <setjmp.h>
2#include <stdbool.h>
3#include <stdio.h>
4#include <stdlib.h>
5
6#include "csv.h"
7
8bool
9processFile(const char *filename)
10{
11 FILE *in = fopen(filename, "r");
12
13 if ( in == NULL ) {
14 return false;
15 }
16
17 csv_t csv;
18 csv_init(&csv);
19
20 while ( csv_read(&csv, in) ) {
21 const size_t nfields = csv_nfields(&csv);
22 // ...
23 }
24 csv_cleanup(&csv);
25
26 (void) fclose(in);
27 return true;
28}
29
30bool
31processFile_options(const char *filename)
32{
33 FILE *in = fopen(filename, "r");
34
35 if ( in == NULL ) {
36 return false;
37 }
38
39 csv_options_t csv_options = csv_default_options;
40 csv_options.field_delimiter = '"';
41 csv_options.field_separator = ',';
42
43 csv_t csv;
44 csv_init_opt(&csv, &csv_options);
45
46 while ( csv_read(&csv, in) ) {
47 const size_t nfields = csv_nfields(&csv);
48 // ...
49 }
50 csv_cleanup(&csv);
51
52 (void) fclose(in);
53 return true;
54}
55
56static void
57csvErrorHandler(csv_err_t err, void *cb_arg)
58{
59 longjmp(*((jmp_buf *) cb_arg), err);
60}
61
62bool
63processFile_error(const char *filename)
64{
65 FILE *in = fopen(filename, "r");
66
67 if ( in == NULL ) {
68 return false;
69 }
70
71 csv_options_t csv_options = csv_default_options;
72 csv_options.field_delimiter = '"';
73 csv_options.field_separator = ',';
74
75 jmp_buf env;
76 csv_options.cb_error = csvErrorHandler;
77 csv_options.cb_error_arg = &env;
78
79 csv_t csv;
80 csv_init_opt(&csv, &csv_options);
81
82 switch ( setjmp(env) ) {
83 case CSV_ERR_OK:
84 while ( csv_read(&csv, in) ) {
85 const size_t nfields = csv_nfields(&csv);
86 // ...
87 }
88 break;
89
90 case CSV_ERR_OUT_OF_MEMORY:
91 case CSV_ERR_OUT_OF_RANGE:
92 case CSV_ERR_IO_READ:
93 case CSV_ERR_IO_WRITE:
94 csv_cleanup(&csv);
95 break;
96 }
97
98 (void) fclose(in);
99 return true;
100}
101
102int
103main(void)
104{
105 return EXIT_SUCCESS;
106}