commit d666838b2ad0776a1e2bb9fef8e2e8ef6de60278
parent 1f76650300e3a22379f84779f0763967907ebc53
Author: phoebos <ben@bvnf.space>
Date: Sat, 2 Oct 2021 12:47:56 +0000
add flag to optionally scan for header line
Diffstat:
M | Makefile | | | 2 | +- |
M | csv.c | | | 58 | +++++++++++++++++++++++++++++++++++++++++----------------- |
2 files changed, 42 insertions(+), 18 deletions(-)
diff --git a/Makefile b/Makefile
@@ -1,5 +1,5 @@
.POSIX:
-XCFLAGS = $(CFLAGS) -Wall -Wextra -Wpedantic -Og -ggdb3
+XCFLAGS = $(CFLAGS) -Wall -Wextra -Wpedantic -Og -ggdb3 -D_XOPEN_SOURCE=600
csv: csv.c
$(CC) $(XCFLAGS) -o $@ $<
diff --git a/csv.c b/csv.c
@@ -36,33 +36,57 @@ read_header(FILE *f, char ***header) {
int
main(int argc, char **argv) {
- if (argc > 2) {
- fprintf(stderr, "usage: %s [file]\n\tif no filename given, data is \
-read from stdin\n", argv[0]);
+ int c;
+ int flag_H = 0;
+ while ((c = getopt(argc, argv, "H")) != -1) {
+ switch (c) {
+ case 'H':
+ flag_H = 1;
+ break;
+ }
+ }
+ if (argc - optind > 1) {
+ 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 == 1) {
+ if (argc - optind == 0) {
f = stdin;
} else {
- f = fopen(argv[1], "r");
+ f = fopen(argv[optind], "r");
if (f == NULL) {
- perror(argv[1]);
+ perror(argv[optind]);
return 1;
}
}
- int ncols;
+ int ncols = 0;
- /* read header */
- 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]);
+ if (flag_H) {
+ /* read header */
+ 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]);
+ }
+ printf("\n");
+ free(header);
+ } else {
+ /* scan the first line to get the value of ncols */
+ while ((c = fgetc(f)) != EOF) {
+ if (c == ',') ncols++;
+ if (c == '\n') {
+ ncols++;
+ break;
+ }
+ }
+ /* ensure we can properly scan the first line when we come to it */
+ rewind(f);
}
- printf("\n");
- free(header);
/* read data */
char *n = malloc(MAX_LINE);
@@ -80,7 +104,7 @@ read from stdin\n", argv[0]);
goto fail;
}
np = n;
- int c, x, y;
+ int x, y;
x = y = 0;
while ((c = fgetc(f)) != EOF) {
if (c == ',' || c == '\n') {
@@ -119,7 +143,7 @@ read from stdin\n", argv[0]);
printf("%g\t", data[i][j]);
printf("\n");
}
- printf("table has %d rows of %d columns\n", nrows, ncols);
+ fprintf(stderr, "table has %d rows of %d columns\n", nrows, ncols);
free(n);
free(data);