aboutsummaryrefslogtreecommitdiff
path: root/csv-test.c
blob: b2d210a3db647e3b882bc614d47313dcc49000b5 (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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <signal.h>
#include <time.h>

#include "csv.h"

static int
test(FILE *f)
{
	int line = 0;
	csv_t csv[1];

	csv_init(csv);
	for ( int n; (n = csv_read(csv, f)) != -1; ) {
		++line;
	}

	return line;
}

static int
test_exception(FILE *f)
{
	int line = 0;
	csv_t csv[1];

	csv_init(csv);
	for ( int n; (n = csv_read(csv, f)) != -1; ) {
		if (++line == 500000) csv_field(csv, -1);
	}

	return line;
}

static void
my_signal_handler(int sig)
{
	if ( sig == SIGABRT ) {
		fprintf(stderr, "my_signal_handler!\n");
		exit(1);
	}
}

static int
test_exception_with_signal(FILE *f)
{
	void (*old_handler)(int) = signal(SIGABRT, my_signal_handler);

	int line = 0;
	csv_t csv[1];

	csv_init(csv);
	for ( int n; (n = csv_read(csv, f)) != -1; ) {
		if (++line == 500000) csv_field(csv, -1);
	}

	signal(SIGABRT, old_handler);

	return line;
}

static void
my_error_handler(const char *msg, void *env)
{
	fprintf(stderr, "my_error_handler: %s\n", msg);
	longjmp(*((jmp_buf *) env), 1);
}

static int
test_exception_longjmp(FILE *f)
{
	/* start with default options */
	csv_options_t csv_options = csv_default_options;

	/* setup error handler */
	jmp_buf env;
	csv_options.cb_error = my_error_handler;
	csv_options.cb_arg = &env;

	/* setup csv-Object with custom options */
	csv_t csv[1];
	csv_init_opt(csv, &csv_options);

	if ( setjmp(env) == 0 ) {
		int line = 0;

		for ( int n; (n = csv_read(csv, f)) != -1; ) {
			// process data...
			if (++line == 500000) csv_field(csv, -1);
		}
		return line;
	}
	else {
		csv_cleanup(csv);
		return -1;
	}
}

int
main(void)
{
	FILE *in = fopen("500000 Records.csv", "r");
	if ( in == NULL ) {
		fprintf(stderr, "failed to open testfile...\n");
		return EXIT_FAILURE;
	}

	clock_t start = clock();

	int lines = test(in);
	(void) test_exception;
	(void) test_exception_with_signal;
	(void) test_exception_longjmp;

	clock_t end = clock();

	fclose(in);

	printf("%d lines processed, duration: %.3lf sec\n", lines, ((double)(end - start)) / CLOCKS_PER_SEC);

	return EXIT_SUCCESS;
}