在C中拆分路径字符串

时间:2014-12-03 00:26:38

标签: c path filesystems

假设我有一个字符串文件的路径(作为我的函数的参数),如下所示:

"foo/foobar/file.txt"

foofoobar是目录

我如何分割这个路径文件,以便我有如下所示的字符串?:

char string1[] = "foo"
char string2[] = "foobar"
char string3[] = "file.txt"

1 个答案:

答案 0 :(得分:1)

" strtok的"被认为是不安全的。您可以在此处找到有关它的更多详细信息:

  

Why is strtok() Considered Unsafe?

因此,您不必使用strtok,而只需将' /' s替换为' \&39; s然后使用' strdup'拆分路径。您可以在下面找到以下实现:

#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;
}

请注意,存在更好的实现,它只在路径上迭代一次并使用&#34; realloc&#34; s在必要时为指针分配更多内存。