summaryrefslogtreecommitdiffstats
path: root/depipe_strings.c
blob: 61115d78871cd16ee590e9a19f75b5cf6096c65f (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
83
84
85
86
87
88
89
90
/* depipe_strings.c
 *
 * Depipe apps into strings
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>

char **depipe_string(const char *, int *);

int main(int argc, char **argv)
{
    int count;
    char *line = "   ls -1      |   wc -l | cut -b 6-7";
    char **depiped = depipe_string(line, &count);

    int j;
    for (j = 0; j < count; j++)
        printf("app %d: %s\n", j+1, depiped[j]);

    free(depiped);

    return 0;
}

/* chops and counts strings with arguments that are separated by pipes */
char **depipe_string(const char *line, int *count)
{
    char *last = (char *) line;
    char *curr = NULL;

    int i;
    int num_apps = 10;
    int fname = 100;
    char **piped_apps = (char **) malloc(sizeof(char *) * num_apps);
    piped_apps[0] = malloc(sizeof(char) * num_apps * fname);

    /* construct m-dimensional array from 1 block of memory */
    for (i = 1; i < num_apps; i++)
        piped_apps[i] = piped_apps[0] + (i * fname);

    *count = 0;
    i = 0;
    int j = 0;
    size_t line_delta = 0;

    while ( (curr = strchr(last, '|')) )
    {
        /* skip white space */
        while (last[0] == ' ')
            last++;

        line_delta = curr - last;
        strncpy(piped_apps[i], last, line_delta);
        piped_apps[i][line_delta] = '\0';

        /* delete whitespace at the tail */
        j = line_delta - 1;
        while (piped_apps[i][j] == ' ')
            piped_apps[i][j--] = '\0';

        last = curr + 1;
        i++;
    }

    /* copy over last item */

    /* skip white space */
    while (last[0] == ' ')
        last++;

    line_delta = line + strlen(line) - (last-1);
    strncpy(piped_apps[i], last, line_delta);
    piped_apps[i][line_delta] = '\0';

    /* delete whitespace at the tail */
    j = strlen(piped_apps[i]) - 1;
    while (piped_apps[i][j] == ' ')
        piped_apps[i][j--] = '\0';

    i++;

    *count = i;
    return piped_apps;
}