diff options
| author | Abigail <abigail@abigail.be> | 2021-04-29 18:30:26 +0200 |
|---|---|---|
| committer | Abigail <abigail@abigail.be> | 2021-04-29 18:30:26 +0200 |
| commit | 05dd9f8ec4afdbc5f332ca61f851a0cb76f10a64 (patch) | |
| tree | 671b5a779e5f8ce387c9466deb4ec12d33f02499 | |
| parent | c7a884422fee8df483e3e88abdf372b1ebbe7415 (diff) | |
| download | perlweeklychallenge-club-05dd9f8ec4afdbc5f332ca61f851a0cb76f10a64.tar.gz perlweeklychallenge-club-05dd9f8ec4afdbc5f332ca61f851a0cb76f10a64.tar.bz2 perlweeklychallenge-club-05dd9f8ec4afdbc5f332ca61f851a0cb76f10a64.zip | |
C solution for week 110, part 2
| -rw-r--r-- | challenge-110/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-110/abigail/c/ch-2.c | 83 |
2 files changed, 84 insertions, 0 deletions
diff --git a/challenge-110/abigail/README.md b/challenge-110/abigail/README.md index c8c826c8cd..33d02ed67b 100644 --- a/challenge-110/abigail/README.md +++ b/challenge-110/abigail/README.md @@ -78,6 +78,7 @@ sex,m,m,f,f ### Solutions * [AWK](awk/ch-2.awk) * [Bash](bash/ch-2.ch) +* [C](c/ch-2.c) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-110/abigail/c/ch-2.c b/challenge-110/abigail/c/ch-2.c new file mode 100644 index 0000000000..fe91fbaec8 --- /dev/null +++ b/challenge-110/abigail/c/ch-2.c @@ -0,0 +1,83 @@ +# include <stdlib.h> +# include <stdio.h> +# include <string.h> + +/* + * See ../README.md + */ + +/* + * Run as: cc -o ch-2.o ch-2.c; ./ch-2.o < input-file + */ + +int main (void) { + char * text = NULL; + size_t len = 0; + size_t str_len; + + if ((str_len = getdelim (&text, &len, '\0', stdin)) == -1) { + perror ("Failed to read stdin"); + exit (1); + } + /* + * Count the number of input lines and columns. + */ + size_t nr_of_lines = 0; + size_t nr_of_columns = 0; + char * ptr = text; + while (* ptr) { + if (nr_of_lines == 0) { + if (* ptr == ',' || * ptr == '\n') { + nr_of_columns ++; + } + } + if (* ptr ++ == '\n') { + nr_of_lines ++; + } + } + + /* + * Position pointer at the start of each input line; + * turn newlines into commas. + */ + char ** outputs; + if ((outputs = (char **) malloc (nr_of_lines * sizeof (char *))) + == NULL) { + perror ("Malloc failed"); + exit (1); + } + ptr = text; + size_t c = 0; + outputs [0] = ptr; + while (* ptr) { + if (* ptr == '\n') { + * ptr = ','; + if (* (ptr + 1) != '\0') { + outputs [++ c] = ptr + 1; + } + } + ptr ++; + } + + /* + * For each line of output, print a column of input. + * Field are terminated by commas. For the output, proceed + * each field with a comma, except for the first output column. + */ + for (size_t i = 0; i < nr_of_columns; i ++) { + for (size_t j = 0; j < nr_of_lines; j ++) { + if (j) { + printf (","); + } + while (* outputs [j] != ',') { + printf ("%c", * outputs [j] ++); + } + outputs [j] ++; + } + printf ("\n"); + } + + + free (text); + return (0); +} |
