summaryrefslogtreecommitdiffstats
path: root/strpbrk.c
blob: 4d614d7ba1238e4fd0d23571f797cf741c7472b6 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char **redir_chop(const char *line)
{
    if (!line)
        return NULL;

    const char *redir_delim = "><";

    char *pipe_redir = strpbrk(line, redir_delim);
    if (pipe_redir == NULL)
        return NULL;

    size_t redir_delta = pipe_redir - line;
    char *former = (char *) malloc(sizeof(char) * 100);
    char *latter = (char *) malloc(sizeof(char) * 100);

    strncpy(former, line, redir_delta);
    former[redir_delta] ='\0';

    /* delete spaces at the end of former string */
    int i = strlen(former) - 1;
    while (former[i] == ' ')
        former[i--] = '\0';

    /* skip spaces in latter string and then copy over */
    int j = redir_delta;
    while (line[++j] == ' ')
        ;
    strncpy(latter, line+j, (line + strlen(line)) - pipe_redir);

    char **ret = (char **) malloc(sizeof(char *) * 2);
    ret[0] = (char *) former;
    ret[1] = (char *) latter;

    return ret;
}

int main(int argc, char *argv[])
{
    const char *line = "ls -1 -al > filename.txt";

#if 0
    const char *redir_delim = "><";

    char *pipe_redir = strpbrk(line, redir_delim);
    size_t redir_delta = pipe_redir - line;
    char *former = (char *) malloc(sizeof(char) * 100);
    char *latter = (char *) malloc(sizeof(char) * 100);

    strncpy(former, line, redir_delta);
    former[redir_delta] ='\0';

    /* delete spaces at the end of former string */
    int i = strlen(former) - 1;
    while (former[i] == ' ')
        former[i--] = '\0';

    /* skip spaces in latter string and then copy over */
    int j = redir_delta;
    while (line[++j] == ' ')
        ;
    strncpy(latter, line+j, (line + strlen(line)) - pipe_redir);

    printf("former string: \"%s\"\n", former);
    printf("latter string: \"%s\"\n", latter);

    free(former);
    free(latter);
#endif

    char **chopped = redir_chop(line);
 
    printf("former string: \"%s\"\n", chopped[0]);
    printf("latter string: \"%s\"\n", chopped[1]);   
    
    return 0;
}