aboutsummaryrefslogtreecommitdiff
path: root/challenge-208/duncan-c-white/C/csvsplit.c
blob: 20e375dabbbcc6aadc94aa3ee8a4fa6cddb1a515 (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
/*
 * csvsplit.c: simple CSV splitting (csvForeach), useful utility function
 *
 * (C) Duncan C. White, May 2017
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>

#include "csvsplit.h"


/*
 * csvForeach( csvstring, &foreach_callback, (void *)extravalue );
 *	Split csvstring into each comma-separated field, calling the
 *	foreach calback for each comma-separated field, passing the
 *	value and extravalue as parameters to it.  It doesn't deal
 *	with commas in quoted strings, however.
 */
void csvForeach( char *csvstring, csvforeachcb cb, void *extra )
{
	// we need to modify the string, so make a mutable copy..
	char *copy = strdup( csvstring );

	char *start = copy;
	for(;;)
	{
		char *comma=strchr( start, ',' );
		if( comma != NULL )
		{
			// found the first comma after start
			*comma = '\0';
		}
		//printf( "debug: csvForeach: found value %s\n", start );
		(*cb)( start, extra );

	if( comma == NULL ) break;

		// move start to one beyond where comma was..
		start = comma+1;
	}
	// don't forget to..
	free( copy );
}