在C中拆分路径字符串

在C中拆分路径字符串,c,path,filesystems,C,Path,Filesystems,假设我有一个字符串形式的文件路径(作为函数的参数),如下所示: "foo/foobar/file.txt" 其中foo和foobar是目录 我将如何拆分此路径文件,以获得如下字符串: char string1[] = "foo" char string2[] = "foobar" char string3[] = "file.txt" “strtok”被认为是不安全的。您可以在此处找到更多详细信息: 因此,您不必使用strtok,只需将“/”替换为“\0”,然后使用“strdup”分割路径

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

"foo/foobar/file.txt"
其中
foo
foobar
是目录

我将如何拆分此路径文件,以获得如下字符串:

char string1[] = "foo"
char string2[] = "foobar"
char string3[] = "file.txt"
“strtok”被认为是不安全的。您可以在此处找到更多详细信息:

因此,您不必使用strtok,只需将“/”替换为“\0”,然后使用“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;
}
#包括
#包括
#包括
字符**拆分(字符*路径,整数*大小)
{
char*tmp;
char**splitted=NULL;
int i,长度;
如果(!路径){
转到出口;
}
tmp=strdup(路径);
长度=strlen(tmp);
*尺寸=1;
对于(i=0;i
请注意,存在更好的实现,它只在路径上迭代一次,并在必要时使用“realloc”为指针分配更多内存