Skip to content

Instantly share code, notes, and snippets.

@pczajkowski
Last active October 16, 2020 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pczajkowski/174c89cb054f1f31fc5e4f0258c27167 to your computer and use it in GitHub Desktop.
Save pczajkowski/174c89cb054f1f31fc5e4f0258c27167 to your computer and use it in GitHub Desktop.
/*
csvtest - reads CSV data from stdin and output properly formed equivalent
useful for testing the library
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <csv.h>
#define TOTALROWS 14
#define TOTALCOLUMNS 18
int row = 0;
int column = 0;
char *array[TOTALROWS][TOTALCOLUMNS];
void cb1 (void *s, size_t i, void *p) {
(void)p;
if (i != 0 ) {
array[row][column] = malloc(i+1);
strncpy(array[row][column], s, i);
*(array[row][column]+i) = 0;
} else {
array[row][column] = NULL;
}
column++;
}
void cb2 (int c, void *p) {
(void)c;
(void)p;
column = 0;
row++;
}
int main (void) {
struct csv_parser p;
int i;
char c;
csv_init(&p, 0);
while ((i=getc(stdin)) != EOF) {
c = i;
if (csv_parse(&p, &c, 1, cb1, cb2, NULL) != 1) {
fprintf(stderr, "Error: %s\n", csv_strerror(csv_error(&p)));
exit(EXIT_FAILURE);
}
}
csv_fini(&p, cb1, cb2, NULL);
csv_free(&p);
for(int i = 0; i < TOTALROWS; i++) {
for(int j = 0; j < TOTALCOLUMNS; j++) {
if (array[i][j] != NULL) {
printf("%s ", array[i][j]);
free(array[i][j]);
}
}
printf("\n");
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment