diff options
Diffstat (limited to 'depipe_strings.c')
-rw-r--r-- | depipe_strings.c | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/depipe_strings.c b/depipe_strings.c new file mode 100644 index 0000000..597ade8 --- /dev/null +++ b/depipe_strings.c @@ -0,0 +1,89 @@ +/* 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 -n1 | less | rtfm| bro "; + 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; +} + +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; +} + |