aboutsummaryrefslogtreecommitdiff
path: root/challenge-110/abigail/c/ch-2.c
blob: 1c0667e45e97fe410906e0d1812d27780abc4e67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# 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);
}