/* depipe_strings.c * * Depipe apps into strings * */ #include #include #include #include #include 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; }