summaryrefslogtreecommitdiffstats
path: root/strsep.c
blob: 882a1e0291b4f94199a30b756ad560544526e7fc (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    char *line = "ls -1 | wc -l | less";

    size_t sz = strlen(line) + 1;
    char *linecopy = malloc(sizeof(char) * sz);
    strcpy(linecopy, line);
    linecopy[sz-1] = '\0';

    char *args[10];
    char **lineptr = &linecopy;

    char *tok = NULL;
    const char arg_delim = ' ';
    int i = 0;

    do
    {
        tok = strsep(lineptr, &arg_delim);
        args[i] = tok;
        i++;
    }
    while ((tok != NULL) && (i < 9));
    
    if (i == 10)
        args[9] = NULL;

    /* print out the piped string */
    int j;    
    for (j = 0; j < i; j++)
        printf("string argument %d: \"%s\"\n", j, args[j]);

    return 0;
}