csv

Unnamed repository
Log | Files | Refs

commit 1f76650300e3a22379f84779f0763967907ebc53
parent 5cd26a74f359f4b33ac0a133fc041a0f49afdaee
Author: phoebos <ben@bvnf.space>
Date:   Sat,  2 Oct 2021 11:59:05 +0000

move header reading into its own function

Diffstat:
Mcsv.c | 63+++++++++++++++++++++++++++++++++++++++------------------------
1 file changed, 39 insertions(+), 24 deletions(-)

diff --git a/csv.c b/csv.c @@ -6,6 +6,34 @@ #define MAX_LINE 2048 +/* read_header reads each header field name from the first line of the file + * into *header, and returns the number of columns. + * This function mallocs the returned value of fields in *header[0..n-1] + */ +int +read_header(FILE *f, char ***header) { + char **headerp = *header; + int c; + int ncols = 0; + char *n = malloc(MAX_LINE); + char *np = n; + while ((c = fgetc(f)) != EOF) { + if (c == ',' || c == '\n') { + *np++ = '\0'; + *headerp = malloc(sizeof n * sizeof *n); + strcpy(*headerp, n); + headerp++; + np = n; + ncols++; + if (c == '\n') break; + continue; + } + *np++ = c; + } + free(n); + return ncols; +} + int main(int argc, char **argv) { if (argc > 2) { @@ -24,34 +52,21 @@ read from stdin\n", argv[0]); } } - char **header = malloc(sizeof (char *) * MAX_LINE); - char **headerp = header; + int ncols; /* read header */ - int c; - int ncols = 0; - char *n = malloc(MAX_LINE); - char *np = n; - while ((c = fgetc(f)) != EOF) { - if (c == ',' || c == '\n') { - *np++ = '\0'; - *headerp = malloc(sizeof n * sizeof *n); - strcpy(*headerp, n); - headerp++; - np = n; - ncols++; - if (c == '\n') break; - continue; - } - *np++ = c; + char **header = malloc(sizeof (char *) * MAX_LINE); + ncols = read_header(f, &header); + for (int i = 0; i < ncols; i++) { + printf("%s\t", header[i]); + free(header[i]); } - do { - printf("%s ", *header); - free(*header); - } while (*++header); - puts(""); + printf("\n"); + free(header); /* read data */ + char *n = malloc(MAX_LINE); + char *np = n; int nrows = 0; float **data; data = malloc(sizeof (float *) * (nrows + 1)); @@ -65,7 +80,7 @@ read from stdin\n", argv[0]); goto fail; } np = n; - int x, y; + int c, x, y; x = y = 0; while ((c = fgetc(f)) != EOF) { if (c == ',' || c == '\n') {