csv

Unnamed repository
Log | Files | Refs

commit c13189446dd8f040b669db70ea5fd93a62959fc5
parent ba408993ea59685a9be3d9bc837f31c2ec45e47e
Author: aabacchus <ben@bvnf.space>
Date:   Sat,  2 Oct 2021 20:28:16 +0100

add csv_read_file function

Diffstat:
Mcsv.c | 49+++++++++++++++++++++++++++++++------------------
1 file changed, 31 insertions(+), 18 deletions(-)

diff --git a/csv.c b/csv.c @@ -12,6 +12,9 @@ struct csv { float **data; /* array of arrays of floats */ }; +int +csv_read_file(FILE *, struct csv *, char hdr); + struct csv * csv_create(void) { struct csv *c; @@ -157,7 +160,7 @@ cleanup: int main(int argc, char **argv) { int c; - int flag_H = 0; + char flag_H = 0; while ((c = getopt(argc, argv, "Hh")) != -1) { switch (c) { case 'H': @@ -174,6 +177,7 @@ usage: " -H\tread data headers from first line\n", argv[0]); return 1; } + FILE *f; if (argc - optind == 0) { f = stdin; @@ -185,22 +189,35 @@ usage: } } - int ncols = 0; - struct csv *csv = csv_create(); + if (csv == NULL) { + perror("csv_create"); + return 1; + } + int ret = csv_read_file(f, csv, flag_H); + if (ret != 0) { + csv_destroy(csv); + return 1; + } + return 0; +} - if (flag_H) { +int +csv_read_file(FILE *f, struct csv *c, char hdr) { + int ch; + int ncols = 0; + if (hdr) { /* read header */ - ncols = read_header(f, csv->headers); + ncols = read_header(f, c->headers); for (int i = 0; i < ncols; i++) { - printf("%s\t", csv->headers[i]); + printf("%s\t", c->headers[i]); } printf("\n"); } else { /* scan the first line to get the value of ncols */ - while ((c = fgetc(f)) != EOF) { - if (c == ',') ncols++; - if (c == '\n') { + while ((ch = fgetc(f)) != EOF) { + if (ch == ',') ncols++; + if (ch == '\n') { ncols++; break; } @@ -208,24 +225,20 @@ usage: /* ensure we can properly scan the first line when we come to it */ rewind(f); } - csv->cols = ncols; + c->cols = ncols; /* read data */ - int nrows = read_data(f, &csv->data, ncols); + int nrows = read_data(f, &c->data, ncols); fclose(f); if (nrows == -1) { - csv_destroy(csv); + csv_destroy(c); return 1; } for (int i = 0; i < nrows; i++) { for (int j = 0; j < ncols; j++) - printf("%g\t", csv->data[i][j]); + printf("%g\t", c->data[i][j]); printf("\n"); } - csv->rows = nrows; - fprintf(stderr, "table has %d rows of %d columns\n", csv->rows, csv->cols); - - csv_destroy(csv); - + c->rows = nrows; return 0; }