【问题标题】:Splitting up a path string in C在C中拆分路径字符串
【发布时间】:2014-12-03 00:26:38
【问题描述】:

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

"foo/foobar/file.txt"

foofoobar 是目录

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

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

【问题讨论】:

    标签: c path filesystems


    【解决方案1】:

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

    Why is strtok() Considered Unsafe?

    因此,您可以简单地将 '/' 替换为 '\0',然后使用 'strdup' 来分割路径,而不是使用 strtok。您可以在下面找到实现:

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

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

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多