csv

Unnamed repository
Log | Files | Refs

commit 4a01eb737eae0d6d454a5cc7090336643886fe25
parent 31c1745c34d6adeb93fcd40d55aa43cedc80b6ec
Author: aabacchus <ben@bvnf.space>
Date:   Sat,  2 Oct 2021 21:25:03 +0100

start manpage, make own library source file

Diffstat:
Acsv.3 | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcsv.c | 3++-
Amain.c | 47+++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 99 insertions(+), 1 deletion(-)

diff --git a/csv.3 b/csv.3 @@ -0,0 +1,50 @@ +.\" To view this file, run: man ./csv.3 +.Dd October 2, 2021 +.Dt CSV 3 +.Os "ben's space" +.Sh NAME +.Nm csv_read_file , +.Nm csv_create , +.Nm csv_destroy +.Nd parse csv data +.Sh LIBRARY +.Lb csv +.Sh SYNOPSIS +.In csv.h +.Bd -literal +struct csv { + int cols, rows; + char **headers; /* array of strings */ + float **data; /* array of arrays of floats */ +}; + +.Ed +.Ft int +.Fn csv_read_file "FILE *stream" "struct csv *c" "char hdr" +.Ft struct csv * +.Fn csv_create +.Ft void +.Fn csv_destroy "struct csv *c" +.Sh DESCRIPTION +These functions reads csv data from +.Va stream +into memory, parsing each cell as a +.Va float . +.Pp +If +.Va hdr +is set, +.Nm +parses the first line of +.Va stream +for column header names which are placed into +.Va c->headers . +.El +.Pp +The number of columns in the first row is set as the intended number +of cells for every row. Extra cells on subsequent rows will be ignored. +Any cells which are empty or missing will be set to +.Va 0 , +and a warning will be printed. +.Sh AUTHORS +.An phoebos Aq Mt ben@bvnf.space diff --git a/csv.c b/csv.c @@ -2,7 +2,6 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <unistd.h> #include "csv.h" #define MAX_LINE 2048 @@ -149,6 +148,7 @@ cleanup: return -1; } +/* int main(int argc, char **argv) { int c; @@ -193,6 +193,7 @@ usage: } return 0; } +*/ int csv_read_file(FILE *f, struct csv *c, char hdr) { diff --git a/main.c b/main.c @@ -0,0 +1,47 @@ +#include <stdio.h> +#include <unistd.h> +#include "csv.h" + +int +main(int argc, char **argv) { + int c; + char flag_H = 0; + while ((c = getopt(argc, argv, "Hh")) != -1) { + switch (c) { + case 'H': + flag_H = 1; + break; + case 'h': + goto usage; + } + } + if (argc - optind > 1) { +usage: + fprintf(stderr, + "usage: %s [-H] [file]\n if no filename given, data is read from stdin\n" + " -H\tread data headers from first line\n", argv[0]); + return 1; + } + + FILE *f; + if (argc - optind == 0) { + f = stdin; + } else { + f = fopen(argv[optind], "r"); + if (f == NULL) { + perror(argv[optind]); + return 1; + } + } + 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; +}