aboutsummaryrefslogtreecommitdiff
path: root/csv-tutorial.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2020-08-21 13:37:11 +0200
committerThomas Schmucker <ts@its1.de>2020-08-21 13:37:11 +0200
commit0ee2ec205c32de9b2563cc4175d1f6d3b65eb220 (patch)
treef075fcf2a1f66c83f8fc7076a03ba57e2e6719e4 /csv-tutorial.c
parentb24ed5ebcd10d3295b009691833dec8f685ff4f6 (diff)
downloadlibcsv-0ee2ec205c32de9b2563cc4175d1f6d3b65eb220.tar.gz
libcsv-0ee2ec205c32de9b2563cc4175d1f6d3b65eb220.tar.bz2
libcsv-0ee2ec205c32de9b2563cc4175d1f6d3b65eb220.zip
fix(doku): Dokumentation überarbeitet und deutlich ausgebaut.
Diffstat (limited to 'csv-tutorial.c')
-rw-r--r--csv-tutorial.c118
1 files changed, 118 insertions, 0 deletions
diff --git a/csv-tutorial.c b/csv-tutorial.c
new file mode 100644
index 0000000..17b95c8
--- /dev/null
+++ b/csv-tutorial.c
@@ -0,0 +1,118 @@
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;
12
13 if ( (in = fopen(filename, "r")) == 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 nf = csv_nfields(&csv);
22 (void) nf;
23 // ...
24 }
25 csv_cleanup(&csv);
26
27 fclose(in);
28 return true;
29}
30
31bool
32processFile_options(const char *filename)
33{
34 FILE *in;
35
36 if ( (in = fopen(filename, "r")) == NULL ) {
37 return false;
38 }
39
40 csv_options_t csv_options = csv_default_options;
41 csv_options.field_delimiter = '"';
42 csv_options.field_separator = ',';
43
44 csv_t csv;
45 csv_init_opt(&csv, &csv_options);
46
47 while ( csv_read(&csv, in) ) {
48 const size_t nf = csv_nfields(&csv);
49 (void) nf;
50 // ...
51 }
52 csv_cleanup(&csv);
53
54 fclose(in);
55 return true;
56}
57
58static void
59csvErrorHandler(csv_err_t err, void *cb_arg)
60{
61 longjmp(*((jmp_buf *) cb_arg), err);
62}
63
64bool
65processFile_error(const char *filename)
66{
67 FILE *in;
68
69 if ( (in = fopen(filename, "r")) == NULL ) {
70 return false;
71 }
72
73 csv_options_t csv_options = csv_default_options;
74 csv_options.field_delimiter = '"';
75 csv_options.field_separator = ',';
76
77 jmp_buf env;
78 csv_options.cb_error = csvErrorHandler;
79 csv_options.cb_error_arg = &env;
80
81 csv_t csv;
82 csv_init_opt(&csv, &csv_options);
83
84 switch ( setjmp(env) ) {
85 case CSV_ERR_OK:
86 while ( csv_read(&csv, in) ) {
87 const size_t nf = csv_nfields(&csv);
88 (void) nf;
89 // ...
90 }
91 break;
92
93 case CSV_ERR_OUT_OF_MEMORY:
94 csv_cleanup(&csv);
95 break;
96
97 case CSV_ERR_OUT_OF_RANGE:
98 csv_cleanup(&csv);
99 break;
100
101 case CSV_ERR_IO_READ:
102 csv_cleanup(&csv);
103 break;
104
105 case CSV_ERR_IO_WRITE:
106 csv_cleanup(&csv);
107 break;
108 }
109
110 fclose(in);
111 return true;
112}
113
114int
115main(void)
116{
117 return EXIT_SUCCESS;
118}