csv

Unnamed repository
Log | Files | Refs

commit 4e1d33e5487d561be4bfb5dfc962718d2689d512
parent 9f1ea74d9dbd70df603318e6ca3fdd6bd473c039
Author: phoebos <ben@bvnf.space>
Date:   Sat,  2 Oct 2021 11:40:42 +0000

read data

Diffstat:
Mcsv.c | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mtest.csv | 11++++++-----
2 files changed, 78 insertions(+), 15 deletions(-)

diff --git a/csv.c b/csv.c @@ -29,30 +29,92 @@ read from stdin\n", argv[0]); /* read header */ int c; + int ncols = 0; char *n = malloc(MAX_LINE); char *np = n; while ((c = fgetc(f)) != EOF) { - fprintf(stderr, "got %c\n", c); - if (c == '\n') goto storeit; - if (c == ',') { - printf("its a ,\n"); -storeit: + if (c == ',' || c == '\n') { *np++ = '\0'; *headerp = malloc(sizeof n * sizeof *n); strcpy(*headerp, n); headerp++; - //*header = n; - //header += sizeof n; - n = np; + np = n; + ncols++; + if (c == '\n') break; continue; } *np++ = c; } - fprintf(stderr, "reading\n"); - do { printf("%s ", *header); + free(*header); } while (*++header); + puts(""); + + /* read data */ + int nrows = 0; + float **data; + data = malloc(sizeof (float *) * (nrows + 1)); + if (data == NULL) { + perror("malloc"); + goto fail; + } + data[0] = malloc(sizeof (float) * ncols); + if (data[0] == NULL) { + perror("malloc"); + goto fail; + } + np = n; + int x, y; + x = y = 0; + while ((c = fgetc(f)) != EOF) { + if (c == ',' || c == '\n') { + if (n == np) { + /* nothing in this column */ + fprintf(stderr, "warning: empty cell at row %d, col %d\n", y + 1, x + 1); + data[y][x] = 0.; + } else { + *np++ = '\0'; + data[y][x] = (float)atof(n); + np = n; + } + x++; + if (c == '\n') { + nrows++; + y++; + x = 0; + data = realloc(data, sizeof (float *) * (nrows + 1)); + if (data == NULL) { + perror("malloc"); + goto fail; + } + data[y] = malloc(sizeof (float) * ncols); + if (data[y] == NULL) { + perror("malloc"); + goto fail; + } + continue; + } + continue; + } + *np++ = c; + } + for (int i = 0; i < nrows; i++) { + for (int j = 0; j < ncols; j++) + printf("%g\t", data[i][j]); + printf("\n"); + } + printf("table has %d rows of %d columns\n", nrows, ncols); + + free(n); + free(data); + + fclose(f); return 0; +fail: + fclose(f); + free(n); + free(data); + return 1; } diff --git a/test.csv b/test.csv @@ -1,5 +1,6 @@ -date,name,quantity -1,me,0 -2,ben,5 -3,mia,123 -4,you,65225 +date,quantity +1,0.166 +2,5 +3,123 +4,65225 +,999