1

Say I have a path to a file in a string (as a argument to my function) as below:

"foo/foobar/file.txt"

Where foo and foobar are directories

How would i go about splitting up this path file so that i have these strings like below?:

char string1[] = "foo"
char string2[] = "foobar"
char string3[] = "file.txt"
user2917692
  • 147
  • 1
  • 3
  • 10

1 Answers1

1

"strtok" is considered not-safe. You can find more details about it here:

Why is strtok() Considered Unsafe?

So instead of using strtok, you can simply replace '/'s with '\0's and then use 'strdup' to split the path. You can find the implementation below:

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

char **split(char *path, int *size)
{
    char *tmp;
    char **splitted = NULL;
    int i, length;

    if (!path){
        goto Exit;
    }

    tmp = strdup(path);
    length = strlen(tmp);

    *size = 1;
    for (i = 0; i < length; i++) {
        if (tmp[i] == '/') {
            tmp[i] = '\0';
            (*size)++;
        }
    }

    splitted = (char **)malloc(*size * sizeof(*splitted));
    if (!splitted) {
        free(tmp);
        goto Exit;
    }

    for (i = 0; i < *size; i++) {
        splitted[i] = strdup(tmp);
        tmp += strlen(splitted[i]) + 1;
    }
    return splitted;

Exit:
    *size = 0;
    return NULL;
}

int main()
{
    int size, i;
    char **splitted;

    splitted = split("foo/foobar/file.txt", &size);

    for (i = 0; i < size; i++) {
        printf("%d: %s\n", i + 1, splitted[i]);
    }

    // TODO: free splitted
    return 0;
}

Note that much better implementations exists, which iterates on the path only once and use "realloc"s to allocate more memory to the pointers when necessary.

Community
  • 1
  • 1
emre.
  • 1,296
  • 11
  • 13